setPreferredOrientations static method

Future<void> setPreferredOrientations(
  1. List<DeviceOrientation> orientations
)

Specifies the set of orientations the application interface can be displayed in.

The orientation argument is a list of DeviceOrientation enum values. The empty list causes the application to defer to the operating system default.

Limitations

Android

Android screens may choose to letterbox applications that lock orientation, particularly on larger screens. When letterboxing occurs on Android, the MediaQueryData.size reports the letterboxed size, not the full screen size. Applications that make decisions about whether to lock orientation based on the screen size must use the display property of the current FlutterView.

// A widget that locks the screen to portrait if it is less than 600
// logical pixels wide.
class MyApp extends StatefulWidget {
  const MyApp({ super.key });

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  ui.FlutterView? _view;
  static const double kOrientationLockBreakpoint = 600;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _view = View.maybeOf(context);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _view = null;
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    final ui.Display? display = _view?.display;
    if (display == null) {
      return;
    }
    if (display.size.width / display.devicePixelRatio < kOrientationLockBreakpoint) {
      SystemChrome.setPreferredOrientations(<DeviceOrientation>[
        DeviceOrientation.portraitUp,
      ]);
    } else {
      SystemChrome.setPreferredOrientations(<DeviceOrientation>[]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Placeholder(),
    );
  }
}

iOS

This setting will only be respected on iPad if multitasking is disabled.

You can decide to opt out of multitasking on iPad, then setPreferredOrientations will work but your app will not support Slide Over and Split View multitasking anymore.

Should you decide to opt out of multitasking you can do this by setting "Requires full screen" to true in the Xcode Deployment Info.

Implementation

static Future<void> setPreferredOrientations(List<DeviceOrientation> orientations) async {
  await SystemChannels.platform.invokeMethod<void>(
    'SystemChrome.setPreferredOrientations',
    _stringify(orientations),
  );
}