Flutter中获取监听屏幕方向、锁定屏幕方向

获取当前屏幕的方向

使用MediaQuery.of(context).orientation

示例:

print("当前屏幕方向:${MediaQuery.of(context).orientation}");

实时监听屏幕方向的改变

使用OrientationBuilder包裹MaterialApp,实现对整个Flutter App的屏幕旋转监听。用法类似于LayoutBuilder

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才会触发。

锁定屏幕方向

使用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()));
}

锁定启动图的方向

在Flutter中指定方向,只能将Flutter启动后内容固定。但是原生端(Android/IOS)的首屏(也叫启动图)还是会根据设备的方向来自适应。

默认效果

默认情况下,Android和IOS都没有开启方向锁定。
当手机处于水平时,如果只是在Flutter中锁定了竖屏,此时启动Flutter App会出现以下效果。

IOS启动效果
IOS启动图方向
Android启动效果
在这里插入图片描述

Android配置

打开android/app/src/main目录下的AndroidManifest.xml
在activity标签中添加属性android:screenOrientation,值为portrait
这样就将Flutter的宿主Activity锁定为了垂直显示。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.surecall.fusion_pro"
    xmlns:tools="http://schemas.android.com/tools">
	
   <application
        android:label="Flutter App"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:screenOrientation="portrait"
            ...>
        </activity>
        ...
    </application>
</manifest>

重新编译运行,查看效果
在这里插入图片描述

IOS配置

打开ios/Runner目录下的Info.plist文件.
找到属性UISupportedInterfaceOrientations,它的值是一个array(数组),默认情况下有4个值,代表支持4个方向,也就是上下左右。

  • UIInterfaceOrientationPortrait:垂直头部朝下
  • UIInterfaceOrientationPortraitUpsideDown:垂直头部朝上
  • UIInterfaceOrientationLandscapeLeft:横屏头部在左
  • UIInterfaceOrientationLandscapeRight:横屏头部在右

另外如果想配置ipad,需要修改属性UISupportedInterfaceOrientations~ipad的值,同上。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	....
	<!--iphone的屏幕方向设置-->
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<!--
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
		-->
	</array>
	<!--ipad的屏幕方向设置-->
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UIViewControllerBasedStatusBarAppearance</key>
	<false/>
</dict>
</plist>

重新编译运行,效果如下
在这里插入图片描述

动态改变Flutter的屏幕方向

DeviceOrientation是一个枚举,有4个值portraitUpportraitDownlandscapeLeftlandscapeRight

竖屏-垂直头部朝下

SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

竖屏-垂直头部朝上

如果在IOS中在plist中没有配置UIInterfaceOrientationPortraitUpsideDown,则不会生效。

SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown]);

横屏-头部显示右边

如果在IOS中在plist中没有配置UIInterfaceOrientationLandscapeRight,则不会生效。

SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight]);

横屏-头部显示左边

如果在IOS中在plist中没有配置UIInterfaceOrientationLandscapeLeft,则不会生效。

SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值