颤振:如何防止设备方向改变并强制纵向?

boe*_*edi 52 dart flutter

我想阻止我的应用程序更改其方向并强制布局坚持"肖像".

在main.dart中,我把:

void main(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  runApp(new MyApp());
}
Run Code Online (Sandbox Code Playgroud)

但是当我使用Android模拟器旋转按钮时,布局"跟随"新的设备方向......

我该怎么解决这个问题?

谢谢

Mas*_*son 96

把方法放在package:flutter/services.dart里面SystemChrome.setPreferredOrientations.

例:

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

  • 如果将 SystemChrome.setPreferredOrientations 放在 main 中,您将收到错误:在初始化绑定之前访问了 ServicesBinding.defaultBinaryMessenger。在构建中插入代码是有效的,因为此时绑定已经初始化。 (5认同)
  • 提醒一下,对于 iOS info.plist,您还必须在 <key>UISupportedInterfaceOrientations~ipad</key> 下为 iPad 设置它 (3认同)

Abe*_*bal 41

打开 android/app/src/main/AndroidManifest.xml 并在 MainActivity 中添加以下行:

android:screenOrientation="portrait"
Run Code Online (Sandbox Code Playgroud)

如果你有这个:

<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">
Run Code Online (Sandbox Code Playgroud)

你应该得到这样的结果:

<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">
Run Code Online (Sandbox Code Playgroud)

这适用于Android。在 iOS 上,您必须从 Xcode 页面更改此设置:https ://i.stack.imgur.com/hswoe.png(如 Hejazi 所说)

  • 谢谢,请记住 configChanges“方向”之后“肖像”的顺序确实很重要。 (2认同)

Tej*_*oid 35

@boeledi,如果你想"锁定"设备方向而不允许它随着用户旋转手机而改变,这很容易设置如下,

// This did not work as requirement
void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  runApp(new MyApp());
}
Run Code Online (Sandbox Code Playgroud)

你必须等到setPreferredOrientations完成然后启动应用程序

// This will works always for lock screen Orientation.
void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
    .then((_) {
      runApp(new MyApp());
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 有时编译时会抛出错误,您应该使用本机解决方案。按照 Abeer Iqbal 的建议,将 'android:screenOrientation="portrait"' 添加到 AndroidManifest 上的 MainActivity 对我来说在 Android 上有效。 (4认同)

小智 34

WidgetsFlutterBinding.ensureInitialized()别人同时建立,你会得到一个错误。

import 'package:flutter/services.dart';

    void main() async => {
          WidgetsFlutterBinding.ensureInitialized();
          await SystemChrome.setPreferredOrientations(
              [DeviceOrientation.portraitUp],
          ); // To turn off landscape mode
          runApp(MainApp());
        };
Run Code Online (Sandbox Code Playgroud)


Pin*_*rji 16

首先在main.dart文件中导入

import 'package:flutter/services.dart';
Run Code Online (Sandbox Code Playgroud)

然后不要复制粘贴而是查看(记住)并在main.dart文件中写入以下代码

要强制使用纵向模式:

void main() {
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp,DeviceOrientation.portraitDown])
      .then((_) => runApp(MyApp()),
  );
Run Code Online (Sandbox Code Playgroud)

强制横向模式:

   void main() {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight])
          .then((_) => runApp(MyApp()),
      );
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提醒人们不要盲目复制粘贴 (2认同)
  • 我明白你为什么要求不要复制粘贴...结尾 } 丢失...我复制粘贴...:) (2认同)

Hej*_*azi 15

对于iOS,调用SystemChrome.setPreferredOrientations()对我不起作用,我必须在Xcode项目中进行更改。

在此处输入图片说明

  • 我从 Android API 级别 8 开始使用“screenOrientation”。@BloodLoss,我想你在文档上读过它,但是关于“resizeableActivity”属性。再次检查链接。^^ (2认同)

Ara*_*yan 13

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

  void main() {
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]).then((_) {
      runApp(new App());
    });
   }
Run Code Online (Sandbox Code Playgroud)

另外,必须导入以下文件:

``package:flutter / services.dart''


Ana*_*nan 13

颤动方向锁定:仅限纵向

\n

在 Flutter 中,我们有 SystemChrome.setPreferredOrientation() (请参阅文档)来定义首选方向。您可以在所有有关 Flutter 中设置方向的文章中找到这种方法。让\xe2\x80\x99s 看看我们如何使用它:

\n
import \'package:flutter/material.dart\';\nimport \'package:flutter/services.dart\';\n\nvoid main() {\n  // We need to call it manually,\n  // because we going to call setPreferredOrientations()\n  // before the runApp() call\n  WidgetsFlutterBinding.ensureInitialized();\n  \n  // Than we setup preferred orientations,\n  // and only after it finished we run our app\n  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])\n      .then((value) => runApp(MyApp()));\n}\n
Run Code Online (Sandbox Code Playgroud)\n

iOS系统

\n

在 Xcode 中打开项目,在项目导航器中(ios/Runner.xcworkspace)选择,选择 Target并在 D 部分的选项卡上RunnerRunnerGeneraleployment Info选项卡上我们可以设置设备方向:

\n

在此输入图像描述

\n

另外,我们可以手动完成,而无需打开 Xcode \xe2\x80\x94 只需编辑ios/Runner/Info.plist. 将其作为文本文件打开,找到密钥UISupportedInterfaceOrientation并仅保留所需的值:

\n
<key>UISupportedInterfaceOrientations</key>\n<array>\n    <string>UIInterfaceOrientationPortrait</string>\n</array>\n
Run Code Online (Sandbox Code Playgroud)\n

安卓

\n

要定义方向,Android我们需要编辑ApplicationManifest. 打开android/app/src/main/AndroidManifest.xml并添加属性 screenOrientationmain

\n
<manifest xmlns:android="http://schemas.android.com/apk/res/android"\n    package="com.example.orientation_lock_example">\n    <application ...>\n        <activity\n            android:name=".MainActivity"\n            android:screenOrientation="portrait"\n            ...\n            />\n            ... \n        </activity>\n        ... \n    </application>\n</manifest>\n
Run Code Online (Sandbox Code Playgroud)\n

这就是\xe2\x80\x99 的全部。这里是带有示例应用程序的存储库:

\n

希望这有帮助。

\n


小智 9

进口import 'package:flutter/services.dart';

然后将下面的代码行包含在您的main.dart文件和 main 方法中,如下所示:

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

runApp(myApp());

Run Code Online (Sandbox Code Playgroud)


Ali*_*bas 8

对于人们来说,他们现在正在阅读这个问题。我找到的最简单的方法,它适用于 android 和 ios 设备。

 void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
    [
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ],
  ).then((val) {
    runApp(YourAppName());
  });
}
Run Code Online (Sandbox Code Playgroud)


Abi*_*san 6

对于 Android,您有两种选择

1. 在main上写

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

AndroidManifest.xml2. 从本机文件设置 在此输入图像描述

对于 iOS,您还有两种选择

1. 来自info.plist

将此行添加到您的info.plist文件中

<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>
Run Code Online (Sandbox Code Playgroud)

2. 从 Runner 打开Runner.xcworkspaceXcode 上的 iOS 文件夹。单击“Runner”而不是“Pod”。您可以在“常规”>“部署信息”中找到此选项。只需检查你想要什么 在此输入图像描述


Rob*_*don 5

setPreferredOrientation返回 a Future<void>,所以它是异步的。最易读的方法是定义main为异步:

Future<void> main() async {
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  return runApp(new MyApp());
}
Run Code Online (Sandbox Code Playgroud)

  • 我强烈不同意。`await` 是一种普遍存在的编程模式,存在于多种语言中,并且非常清楚表达什么。`then` 创建嵌套级别。如果你有三到四个延续,那么 `then` 确实开始变得非常难以阅读。 (3认同)

小智 5

只需在 main.dart 文件中添加以下代码行。

SystemChrome.setPreferredOrientations([
  DeviceOrientation.portraitUp,
]);
Run Code Online (Sandbox Code Playgroud)

并记得导入 services.dart 文件。下面给出一个例子!

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
    runApp(MyApp());
}


class MyApp extends StatelessWidget {
     @override
     Widget build(BuildContext context) {

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

      return MaterialApp(
        home: Scaffold(
          body: Center(child: Text("A Flutter Example!")),
     ),
   );
  }
}
Run Code Online (Sandbox Code Playgroud)