Flutter实现横屏处理(ios特殊处理)

136 阅读1分钟

在app中播放视频或者其他需要支持横屏展示

在Android端直接调用系统方法即可

// 旋转横屏
static void rotateToLandscape () {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);
}
// 竖屏
static void resetOrientation () {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

在iOS端则需要使用到methodChannel来实现。因为ios不允许强制调用横屏

第一步先在flutter内写一个channel方法
import 'package:flutter/services.dart';

class ScreenOrientation {
  // com.xxxxxx.app/screen_orientation  这个channel名称必须对应上
  static const MethodChannel _channel =
  MethodChannel('com.xxxxxx.app/screen_orientation');

  static Future<void> setLandscape() async {
    await _channel.invokeMethod('setLandscape');
  }

  static Future<void> setPortrait() async {
    await _channel.invokeMethod('setPortrait');
  }
}
第二步在iOS目录找到Runner下的AppDelegate.m;如下图

image.png

然后增加自定义channel方法,我这是Flutter3.0版本,ios用的是ObjectC
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;

  // 创建 MethodChannel,用于与 Flutter Dart 代码通信
  FlutterMethodChannel* screenOrientationChannel =
      [FlutterMethodChannel methodChannelWithName:@"com.xxxxxx.app/screen_orientation"
                                  binaryMessenger:controller.binaryMessenger];

  [screenOrientationChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
    // 处理 Flutter Dart 代码发来的方法调用
    if ([call.method isEqualToString:@"setLandscape"]) {
      // 处理横屏切换逻辑
      [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    } else if ([call.method isEqualToString:@"setPortrait"]) {
      // 处理竖屏切换逻辑
      [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
    } else {
      result(FlutterMethodNotImplemented);
    }
  }];
最后在dart文件中需要ios横屏的调用ScreenOrientation类的方法即可
if (Platform.isIOS) {
  ScreenOrientation.setLandscape();
}
```
if (Platform.isIOS) {
  ScreenOrientation.setPortrait();
}
```