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

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

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

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

我怎么解决这个问题呢?

谢谢


当前回答

下面是颤振队的官方例子。 https://github.com/flutter/samples/blob/master/veggieseasons/lib/main.dart

import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;

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

其他回答

导入包:颤振/服务。飞镖,然后

放上SystemChrome。Widget build()方法中的setPreferredOrientations。

例子:

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      return new MaterialApp(...);
    }
  }

更新

如2019年10月更新的flutter文档中所述,此解决方案可能不适用于某些IOS设备。

他们建议通过在信息中设置UISupportedInterfaceOrientations来固定方向。请像这样

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

更多信息https://github.com/flutter/flutter/issues/27235#issuecomment-508995063

如果你从xcode界面编辑这个,它不会在ipad上被改变。对于ipad部分,您必须编辑信息。Plist文件从android工作室。你可以在数组列表中看到“~ ipad”。在info中有两个部分可用。Plist,你必须为iPhone和ipad手动编辑它。

要在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/>

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

setPreferredOrientations方法返回一个Future对象。 对于每个文档,Future表示将来某个地方可用的某个值。这就是为什么您应该等到它可用后再继续应用程序的原因。因此,有应使用'then'方法,根据定义,它“注册当Future完成时要调用的回调”。因此,您将使用以下代码:

  void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]).then((_) {
      runApp(new App());
    });
   }

同时,还需要导入以下文件:

“包:颤振/ services.dart”

下面是颤振队的官方例子。 https://github.com/flutter/samples/blob/master/veggieseasons/lib/main.dart

import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;

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