获取当前屏幕的方向
使用MediaQuery.of(context).orientation
示例:
print("当前屏幕方向:${MediaQuery.of(context).orientation}");
实时监听屏幕方向的改变
使用OrientationBuilder 包裹MaterialApp ,实现对整个Flutter App的屏幕旋转监听。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OrientationBuilder(
builder: (BuildContext context, Orientation orientation) {
print("当前屏幕的方向是:$orientation");
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
},
);
}
}
注意 :
只有当屏幕由垂直变为水平,或者水平变为垂直,此builder才会触发。
控制App的方向
使用SystemChrome.setPreferredOrientations(List<DeviceOrientation> orientations);
锁定方向,禁止App随着设备的方向改变
锁定App的方向为垂直,禁止横屏。
为了防止出现以下异常信息,需要在main方法的第一行加上WidgetsFlutterBinding.ensureInitialized() 。
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.
示例:
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown, DeviceOrientation.portraitUp])
.then((value) => runApp(MyApp()));
}
动态改变App的屏幕方向
DeviceOrientation 是一个枚举,有4个值portraitUp、portraitDown、landscapeLeft、landscapeRight。
竖屏-头部显示顶部
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
竖屏-头部显示底部
但是不知道为什么,只在Android中才有效果,在IOS中设置了不会生效。
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown]);
横屏-头部显示右边
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight]);
横屏-头部显示左边
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
|