设置屏幕方向 :
首先,你需要导入 services 包 :
import 'package:flutter/services.dart';
我们可以通过 SystemChrome
这个类的 setPreferredOrientations方法来设置屏幕方向。
setPreferredOrientations()方法,参数是一个数组 ,我们可以设置多个方向(定义在 DeviceOrientation
枚举类中)。
在Flutter中主函数入口是 main()方法,如果我们想设置整个应用的屏幕方向,在runApp()方法之前设置即可。
注意 : 设置屏幕方法调用之前,需要调用一下 binding 的初始化方法(先记住即可)
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]).then((_){
runApp(MyApp());
});
}
设置屏幕水平方向的方法 :
landscapeLeft or landscapeRight 可以设置一个或者两个,效果试一下就知道了
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight])
设置屏幕垂直方向 :
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown,DeviceOrientation.portraitUp])
动态改变屏幕方向 :
RaisedButton(
child: Text("Portrait"),
onPressed: (){
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
})
获取当前屏幕方向 :
MediaQuery.of(context).orientation
MediaQuery.of(context).orientation == Orientation.landscape
参考 :
https://dev.to/mightytechno/how-to-change-screen-orientation-in-flutter-32c1(自备梯子)
如果觉得文章有用,帮忙点个喜欢❤️ ,😘😘😘 赠人玫瑰,手留余香
网友评论