Sam Cromer
Sam Cromer

Reputation: 2213

Force portrait view in flutter

I have tried using this code I found on a thread on this site but all that happens is my application loads a white screen. Is there a better way to force portrait view in flutter? Seems like simple thing to set.

void main() async {
  ///
  /// Force the layout to Portrait mode
  ///
  await SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

  runApp(new MaterialApp(
    debugShowCheckedModeBanner: false,
    home: LoginScreen(),
  ));
}

Upvotes: 1

Views: 1467

Answers (3)

MichaelM
MichaelM

Reputation: 5838

From the exception in the comment:

Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized

You need to call

WidgetsFlutterBinding.ensureInitialized();

Before your call to SystemChrome.setPreferredOrientations

Upvotes: 1

om-ha
om-ha

Reputation: 3602

Solution

  1. Change your code to this:
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  ///
  /// Force the layout to Portrait mode
  ///
  await SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

  runApp(new MaterialApp(
    debugShowCheckedModeBanner: false,
    home: LoginScreen(),
  ));
}
  1. Open your Xcode project and go to Target -> Deployment Info -> Require Full Screen to true. This will reflect in your ios/Runner/Info.plist to have the following value:
    <key>UIRequiresFullScreen</key>
    <true/>

Description

Well there are a couple of points to be addressed here:

  1. You forgot WidgetsFlutterBinding.ensureInitialized(). This IS important since you're "awaiting" on async main method.
  2. According to setPreferredOrientations's documentation, there's a limitation regarding iPad multitasking:

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

To alleviate #2, from the docs:

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

Upvotes: 1

Khadga shrestha
Khadga shrestha

Reputation: 1180

Change your code as

void main() {
 WidgetsFlutterBinding.ensureInitialized();
 SystemChrome.setPreferredOrientations(
 [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
 .then((_) => runApp(new MaterialApp(
         debugShowCheckedModeBanner: false,
         home: LoginScreen(), 
      )));
}

`

Upvotes: 5

Related Questions