我想阻止我的应用程序改变其方向,并迫使布局坚持“纵向”。
大体上是这样。省道,我放:
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所说)
这个解决方案已经在我的两个不同的Android项目中发挥了作用。不能保证它也适用于iOS。我已经阅读了之前所有的答案,我认为最好和最简单的解决方案是这样做的:
Android:
这样你就避免了所有的“await”,“async”和“then”,这些可能会扰乱你的代码
/// this is in main.dart
main(){
WidgetsFlutterBinding.ensureInitialized();
runApp(
MaterialApp(
initialRoute: '/root',
routes: {
'/root': (context) => MyApp(),
},
title: "Your App Title",
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
/// ENFORCE DEVICE ORIENTATION PORTRAIT ONLY
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown
]);
/// RUN THE APP
return MaterialApp(
home: HomeScreen(),
);
}
}
iOS:
我认为这个答案的更新是iOS的最佳选择。
!! 免责声明! !
我做了一点调查,显然,这里的文档特别说:
setPreferredOrientations method Limitations:
"This setting will only be respected on iPad if multitasking is disabled."
下面是如何在XCode中禁用多任务处理(也就是打开“要求全屏”选项)
iOS的另一个可能的解决方案
你也可以试试这个。我个人还没有尝试过,因为我的电脑上没有iPad或XCode,但它值得一试
@boeledi,如果你想“锁定”设备方向,不允许它随着用户旋转他们的手机而改变,这很容易设置如下:
// This did not work as requirement
void main() {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(new MyApp());
}
你必须等到setPreferredOrientations完成,然后
启动应用程序
// This will works always for lock screen Orientation.
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(new MyApp());
});
}