有解决这个问题的办法吗?

堆栈跟踪:

[VERBOSE-2:ui_dart_state.cc(148)] 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.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:73:7)
#1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:86: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)
<asynchronous suspension>
#4      MethodChannel.invokeMapMethod (package:f<…>

当前回答

只需在main.dart中添加这一行

WidgetsFlutterBinding.ensureInitialized(); 

您的代码看起来像

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  return runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider.value(
        value: AppState(),
      )
    ],
    child: MyApp(),
  ));
}

其他回答

解决方案:调用WidgetsFlutterBinding.ensureInitialized();在调用异步函数之前。


void main() async {
  WidgetsFlutterBinding.ensureInitialized();   //  ADD THIS BEFORE YOUR ASYNC FUNCTION CALL.
  await Firestore.instance.settings(...);      //  NOW YOU CAN CALL ASYNC FUNCTION.   
  ...
  runApp(
    ...
  )

如果您从孤立对象接收到这个错误,那么接受的解决方案就不起作用,这是毫无价值的。

WidgetsFlutterBinding.ensureInitialized();

只确保在主线程上的绑定。 我们正在努力消除这一限制,你可以在这里关注这个问题

https://github.com/flutter/flutter/issues/13937

如果您正在等待main()方法,通常会发生这种情况。所以,解决方案是:

void main() {
  // add this, and it should be the first line in main method
  WidgetsFlutterBinding.ensureInitialized(); 

  // rest of your app code
  runApp(
    MaterialApp(...),
  );
}

如果你试图在一个独立的环境中执行插件原生代码,你可能会遇到这种情况。这里的isolate_handler文档很好地解释了这一点:

插件之间使用一种称为平台通道的机制进行通信 Dart和本机边,消息传递机制使用 MethodChannel类型。这种机制取决于元素 底层UI引擎的功能。

这里的问题是,只有在计算成本高昂的dart代码的情况下,隔离才会提供性能提升。插件的平台代码将再次使用主(UI)线程。

调用WidgetsFlutterBinding。隔离内部的ensureInitialized也会失败,因为隔离中缺少底层UI引擎。

通过在void main()中添加这一行,错误将得到解决。

WidgetsFlutterBinding.ensureInitialized();