用Flutter固定屏幕方向

  • 发表于
  • flutter

以下为我用Flutter固定屏幕方向,也称Flutter禁止横屏坚屏的方法。

静态方法Flutter固定屏幕方向

导包

import 'package:flutter/services.dart';

支持横坚屏切换

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

全局设置

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

很可能会出现这个错误:

E/flutter (12370): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter (12370): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter (12370): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.

在main()中进行异步处理时,应编写以下代码

WidgetsFlutterBinding.ensureInitialized();

Flutter禁止横屏

标准示例main.dart

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

需要注意的是WidgetsFlutterBinding.ensureInitialized();,在异步情况下必须添加否则报错,静态方法中则不需要添加。