Flutter-ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized

升级Flutter版本(1.12.13+hotfix.5)后,原有项目(flutter version:1.9.x),运行起来是白屏,控制台打印出如下信息:

Launching lib/main.dart on iPhone X in debug mode...
Running Xcode build...
Xcode build done.                                           14.7s
[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.
If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
#0      defaultBinaryMessenger. (package:flutter/src/services/binary_messenger.dart:76:7)
#1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:89:4)
#2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
#3      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:314:35)
#4      MethodChannel.invokeMapMethod (package:flutter/src/services/platfo<…>
Syncing files to device iPhone X...

可根据控制台的输出信息,在main.dart文件中的main方法中,在runApp()前显式调用如下代码:

WidgetsFlutterBinding.ensureInitialized();

官方文档:

A concrete binding for applications based on the Widgets framework.
This is the glue that binds the framework to the Flutter engine.

Returns an instance of the [WidgetsBinding], creating and initializing it if necessary. If one is created, it will be a [WidgetsFlutterBinding]. If one was previously initialized, then it will at least implement [WidgetsBinding].
You only need to call this method if you need the binding to be initialized before calling [runApp].
In the flutter_test framework, [testWidgets] initializes the binding instance to a [TestWidgetsFlutterBinding], not a [WidgetsFlutterBinding].

来自谷歌翻译:

基于Widgets框架的应用程序的具体绑定。
这是将框架绑定到Flutter引擎的粘合剂。

返回[WidgetsBinding]的实例,必要时创建并初始化它。 如果创建了一个,它将是一个[WidgetsFlutterBinding]。 如果以前已经初始化过,那么它将至少实现[WidgetsBinding]。
仅在需要在调用[runApp]之前初始化绑定的情况下,才需要调用此方法。
flutter_test框架中,[testWidgets]将绑定实例初始化为[TestWidgetsFlutterBinding],而不是[WidgetsFlutterBinding]。

我这边遇见的情况是,在main方法中,使用了future,我在future调用之前,需要调用WidgetsFlutterBinding.ensureInitialized();,如果不使用future,则没有问题。以下是我的main方法中的代码:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Global.init().then((e) { // Global.init返回一个future
//  run(['src=jsons']);
    debugPaintBaselinesEnabled = false; // 基准线
    debugPaintSizeEnabled = false; // 画布大小
    runApp(MyApp());
  });
}

你可能感兴趣的:(Flutter-ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized)