縦画面を固定にしたく、下記のコードをmain()内のrunApp()前に実行すると、
void main() {
// 画面の向きを固定.
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(MyApp());
}下記エラーが発生しました。
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86) #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36) #2 OptionalMethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:461:18) #3 SystemChrome.setPreferredOrientations (package:flutter/src/services/system_chrome.dart:242:35) #4 main (package:days2/main.dart:8:16) #5 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25) #6 _rootRun (dart:async/zone.dart:1354:13) #7 _CustomZone.run (dart:async/zone.dart:1258:19) #8 _runZoned (dart:async/zone.dart:1789:10) #9 runZonedGuarded (dart:async/zone.dart:1777:12) #10 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5) #11 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19) #12 <…>
他のプロジェクトで利用していた方法なのですが、なぜ。。。。
答えは、
WidgetsFlutterBinding.ensureInitialized();
が必要でした。
void main() {
// runAppを実行する前に、Flutterの初期化
WidgetsFlutterBinding.ensureInitialized();
// 画面の向きを固定。※runApp()を実行する前に、Flutterの機能を利用する
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
// runApp内で
runApp(MyApp());
}ちなみに、iPadでは更なる追加対応が必要です。
まずは、AppDelegate.swiftに下記の2個目のapplication()を追加します。
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(
_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?
) -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask(arrayLiteral:
[UIInterfaceOrientationMask.allButUpsideDown]);
}
}さらに、Xcodeの設定で、「Requires full screen」を有効にします。

これで、iPadでも縦向きに表示させることができます。
