mjsid
mjsid

Reputation: 101

What is WidgetsFlutterBinding and how it is being used in Flutter app?

When and how we use it? How it works?

WidgetsFlutterBinding

Upvotes: 9

Views: 9079

Answers (2)

Jitesh Mohite
Jitesh Mohite

Reputation: 34250

WidgetsBinding.ensureInitialized() This initialised communication between the Dart Layer and Flutter Engine.

We need to call this method if we need the binding to be initialised before calling [runApp]. Flutter cannot directly interact with flutter engine until and unless binding is established.

Example 1: Shows Firebase platform initialisation between flutter and native code, which Firestore class do internally.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();   
  await Firestore.initializeApp();
  runApp(
    ...
  )
}

OR

Example 2: Shows device orientation changes before even app starts, for this also we need to established binding connection.

 void main() async {
      WidgetsFlutterBinding.ensureInitialized();   
      await SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown
      ]);
      runApp(
        ...
      )
}

Internally, WidgetsBinding.ensureInitialized() supports various binding likes GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding

  1. ServicesBinding listens for platform messages and directs them to the handler for incoming messages (BinaryMessenger).

  2. PaintingBinding is responsible for binding to the painting library.

  3. RenderBinding binds the render tree to the Flutter engine.

  4. WidgetBinding binds the widget tree to the Flutter engine.

  5. SchedulerBinding is the scheduler for running immediate tasks.

  6. SemanticsBinding binds the semantics layer and the Flutter engine.

  7. GestureBinding is a binding for the gesture subsystem.

Upvotes: 4

saif aly
saif aly

Reputation: 605

You have to use it, in this way:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

https://flutter.dev/docs/resources/architectural-overview#architectural-layers

The WidgetFlutterBinding is used to interact with the Flutter engine. Firebase.initializeApp() needs to call native code to initialize Firebase, and since the plugin needs to use platform channels to call the native code, which is done asynchronously therefore you have to call ensureInitialized() to make sure that you have an instance of the WidgetsBinding.

Answerd By https://stackoverflow.com/users/7015400/peter-haddad

Answer Link https://stackoverflow.com/a/63873689

Upvotes: 5

Related Questions