Flutter horizontal screen practice

Insert image description here

1. Flutter sets horizontal screen

// 强制横屏
SystemChrome.setPreferredOrientations([
  DeviceOrientation.landscapeLeft,
  DeviceOrientation.landscapeRight
]);
// 强制竖屏
SystemChrome.setPreferredOrientations(
    [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

Another suggestion

1. Encapsulate all horizontal and vertical screen calls into one method to facilitate maintenance

2. If it is turned on, put it behind the super, and if it is turned off, put it in front of the super.


void initState() {
    
    
  super.initState();
  AppUtil().setScreenLandscape(true);
}


void dispose() {
    
    
  AppUtil().setScreenLandscape(false);
  super.dispose();
}

2. Native setting of horizontal screen

In the process of practice, I found that iOS occasionally cannot turn to horizontal screen. If you also encounter this problem, you can consider setting the native horizontal screen.

android native

if (screenLandscape) {
    
    
    // 设置屏幕为横向
   activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
    
    
    // 设置屏幕为纵向
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

If you need system applications such as cameras and photo albums to be able to be used horizontally, you can turn on the permission to allow automatic rotation.

// 检查是否打开自动屏幕旋转
public static boolean checkAutoRotate(Activity activity) {
    
    
    // android系统设置权限
    if (!Settings.System.canWrite(activity)) {
    
    
        activity.runOnUiThread(() -> Toast.makeText(activity, "请允许修改系统设置权限!", Toast.LENGTH_SHORT).show());
        // 没有系统设置权限 -> 跳转到系统设置页面
        new Thread(() -> {
    
    
            try {
    
    
                sleep(500);
            } catch (InterruptedException e) {
    
    
                throw new RuntimeException(e);
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, 1);
        }).start();
        return false;
    } else {
    
    
        // 有系统设置权限 -> 打开手机屏幕方向自动旋转(参数备注:1为开,0为关)
        Settings.System.putInt(activity.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
        return true;
    }
}

ios native

NSDictionary *dict = call.arguments;
bool screenLandscape = [dict[@"screenLandscape"] boolValue];
UIInterfaceOrientation val = screenLandscape ? UIInterfaceOrientationLandscapeLeft : UIInterfaceOrientationPortrait;
[weakSelf ll_interfaceOrientation:val];
result([JYJUtils dictionaryToJson:@{}]);

3. Horizontal and vertical screen adaptation

The horizontal and vertical screen adaptation is implemented on the Flutter side. I only need the horizontal screen here, so when the vertical screen is detected, it will be called again to switch to the horizontal screen.

OrientationBuilder(
  builder: (context, orientation) {
    
    
    if (orientation == Orientation.portrait) {
    
    
      return PortraitPage();
    } else {
    
    
      return LandscapePage();
    }
  },
)

// 竖屏
PortraitPage() {
    
    
  AppUtil().setScreenLandscape(true);
  return Column(
    mainAxisSize: MainAxisSize.max,
    children: [
      CustomBar(
        title: _titleString(longTitle: true),
      ),
      Expanded(
        child: Center(
          child: Text('请旋转横屏使用'),
        ),
      ),
    ],
  );
}

// 横屏
LandscapePage() {
    
    
  final double statusBarHeight =
      Platform.isIOS ? 35 : MediaQuery.of(context).padding.top;
  return Container(
    margin: EdgeInsets.only(top: statusBarHeight, left: 30, right: 30),
  );
}

4. Flutter horizontal screen Android is not fully covered

Screenshot_20231007_140001

Solution
Open the project android/app/src/main/res/values/styles.xml

Add to

<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>
    <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="android:windowBackground">?android:colorBackground</item>
        <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
    </style>
</resources>LaunchTheme下为启动页配置,NormalTheme下为普通页面配置

Guess you like

Origin blog.csdn.net/liuxingyuzaixian/article/details/133643904