Skip to content

[Solved] ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.

When using Flutter to develop an application, if some packages such as firebase or sqflite that need to be initialized, but they are operated asynchronously, we often get the following error message:

ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.


We can see the following Flutter architecture diagram, which is divided into several different blocks such as Framework, Engine, and Embedder. Each block has various modules and functions.

Packages such as firebase and sqflite need these modules and functions to complete initialization. But as mentioned above, these operations are asynchronous. Therefore, we need ensure that object called WidgetBinding has been initialized and established.

In this way, these asynchronously initialized packages can work.


Solution

To put it simply, solving the problem is not complicated.

We can imagine the following process:

  • We have a tool A, and need tool B to work
  • Tool A will be loaded earlier than tool B => the program reports an error!
  • We first write a program to ensure that tool B is loaded, and then load tool A => the program runs successfully!

In other words, we can add in the following code:

WidgetsFlutterBinding.ensureInitialized();


To ensure that WidgetsBinding bas been initialized.

The complete code will look like this:

import 'dart:async';

import 'package:flutter/widgets.dart';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';


void main() async {
  // Avoid errors
  WidgetsFlutterBinding.ensureInitialized();

  // Open the database
  final Future<Database> database = openDatabase(

    // Ensure the path is correctly for any platform
    join(await getDatabasesPath(), "Human_database.db"),
    onCreate: (db, version) {
      return db.execute(
          "CREATE TABLE Human("
              "id INTEGER PRIMARY KEY,"
              "name TEXT,"
              "age INTEGER,"
              "FAT BOOLEAN)"
      );
    },

    // Set the database version
    version: 1,
  );

  print("OK!");
}


Output:

OK!


It can be found that delete the following line

WidgetsFlutterBinding.ensureInitialized();


Will get error.


References


Read More

Tags:

Leave a Reply