我想阻止我的应用程序改变其方向,并迫使布局坚持“纵向”。

大体上是这样。省道,我放:

void main(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(new MyApp());
}

但当我使用Android模拟器旋转按钮时,布局“遵循”新的设备方向…

我怎么解决这个问题呢?

谢谢


当前回答

打开android/app/src/main/AndroidManifest.xml,在MainActivity中添加如下一行:

android:screenOrientation="portrait"

如果你有这个:

<activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">

你应该得到这样的结果:

<activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">

这适用于Android。在iOS上,你将不得不从Xcode页面更改:https://i.stack.imgur.com/hswoe.png(正如Hejazi所说)

其他回答

要在iPad中强制竖屏,你还必须修改关键的UISupportedInterfaceOrientations~ iPad in ios/Runner/Info.plist:

    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
            <string>UIInterfaceOrientationPortrait</string>
            <string>UIInterfaceOrientationPortraitUpsideDown</string>
    </array>

这也可以通过XCode实现。

以上将在本地工作。为了通过XCode上传到App Store,你还需要将以下内容添加到Info.plist。这也可以通过检查“目标->常规->部署信息”下的“要求全屏”来完成。

   <key>UIRequiresFullScreen</key>
   <true/>

否则你会在上传时得到一个错误。

导入导入“包:flutter/services.dart”;

然后在main中包含下面这行代码。Dart文件,并在你的main方法中像这样:

WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitDown,
    DeviceOrientation.portraitUp,
  ]);

runApp(myApp());

Try

 void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]); 
    
      runApp(MyApp());
 }

你也可以在android manifest和ios info中更改屏幕方向设置。plist文件。

android有两个选项

1. 写在主

    main() {
      WidgetsFlutterBinding.ensureInitialized();
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
          .then((_) {
        runApp(
          child: MyApp(),
        );
      });
}

2. 在AndroidManifest.xml文件中设置

iOS上也有两种选择

1. 从info.plist

将这一行添加到您的信息中。plist文件

<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>

2. 从跑步者 打开你的奔跑者。Xcode的iOS文件夹中的xcworkspace。点击Runner而不是Pods。您可以在“常规>部署信息”上找到此选项。看看你想要什么

这是一个简单的方法->

SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);