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

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

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

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

我怎么解决这个问题呢?

谢谢


当前回答

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

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

其他回答

iOS:

调用SystemChrome.setPreferredOrientations()对我来说不起作用,我必须在Xcode项目中更改设备方向,如下所示:

Android:

在文件android/app/src/main/AndroidManifest.xml中设置主活动的screenOrientation属性为portrait,如下所示:

放置WidgetsFlutterBinding.ensureInitialized(),否则在构建时将得到一个错误。

import 'package:flutter/services.dart';

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

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

这是一个简单的方法->

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

颤振方向锁定:仅限纵向

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

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

void main() {
  // We need to call it manually,
  // because we going to call setPreferredOrientations()
  // before the runApp() call
  WidgetsFlutterBinding.ensureInitialized();
  
  // Than we setup preferred orientations,
  // and only after it finished we run our app
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((value) => runApp(MyApp()));
}

iOS

在Xcode (ios/Runner.xcworkspace)中打开项目,在项目导航器中选择运行器,选择目标运行器,在“常规”选项卡的“部署信息”部分,我们可以设置设备方向:

同样,我们也可以在不打开Xcode的情况下手动完成——只需编辑ios/Runner/Info.plist。将其作为文本文件打开,找到键UISupportedInterfaceOrientation,只留下所需的值:

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>

安卓

为了定义Android的方向,我们需要编辑ApplicationManifest。打开android/app/src/main/AndroidManifest.xml,为主活动添加属性screenOrientation:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.orientation_lock_example">
    <application ...>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            ...
            />
            ... 
        </activity>
        ... 
    </application>
</manifest>

就这些。下面是一个示例应用程序的存储库:

希望这对你有帮助。