0

I am trying to force my Flutter app to only use Portrait mode. My main() method looks like this.

void main() {
  SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
  SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS)
  .then((_) => runApp(MyApp()));
}

Here is the definition of ALLOWED_ORIENTATIONS:

const List<DeviceOrientation> ALLOWED_ORIENTATIONS = [
  DeviceOrientation.portraitUp
];

I just separated all the settings and such to another file to make modifying them later on easier.

When I run this code, I get the following error.

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
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.

It looks like there is some race condition that's failing. I am just not sure what is causing it. Removing the SystemChrome.setPreferredOrientations() line makes the app compile as expected. So, I am thinking the error has something to do with that line.

Any advice?

Patrick Lumenus
  • 1,412
  • 1
  • 15
  • 29
  • https://www.didierboelens.com/2018/04/hint-3-how-to-force-the-application-to-stick-to-portrait-mode/ – Wenhui Luo Jan 24 '20 at 22:38
  • It’s still giving me the error. – Patrick Lumenus Jan 24 '20 at 22:48
  • Does this answer your question? [Flutter: Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized](https://stackoverflow.com/questions/57689492/flutter-unhandled-exception-servicesbinding-defaultbinarymessenger-was-accesse) –  Jan 24 '20 at 23:06

1 Answers1

1

Like the error says

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.

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
  await SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS);

  runApp(MyApp());  
}
Crazy Lazy Cat
  • 13,595
  • 4
  • 30
  • 54