【Flutter】画面の向きを縦や横に固定する


縦固定するなら main.dart にこのように書く。

main.dart
void main(){
  WidgetsFlutterBinding.ensureInitialized();
  //向き指定
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,//縦固定
  ]);
  //runApp
  runApp(MyApp());
}

WidgetsFlutterBinding.ensureInitialized() を最初に書かないと起動時に以下のようなエラーメッセージが出てしまうので、書いておきましょう。

FlutterError (ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
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.
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.)

参考: https://github.com/flutter/flutter/issues/40253

DeviceOrientation

以下の4パターンの指定ができます。

enum DeviceOrientation {
  portraitUp,
  landscapeLeft,
  portraitDown,
  landscapeRight,
}