Reputation: 101
When and how we use it? How it works?
Upvotes: 9
Views: 9079
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
ServicesBinding
listens for platform messages and directs them to the handler for incoming messages (BinaryMessenger).
PaintingBinding
is responsible for binding to the painting library.
RenderBinding
binds the render tree to the Flutter engine.
WidgetBinding
binds the widget tree to the Flutter engine.
SchedulerBinding
is the scheduler for running immediate tasks.
SemanticsBinding
binds the semantics layer and the Flutter engine.
GestureBinding
is a binding for the gesture subsystem.
Upvotes: 4
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