在flutter项目中,有的时候我们需要初始化一些第三方插件,如果插件是异步函数执行的,我们就需要将main函数设置为 async 。这样就会出现如下错误。
E/flutter (21626): [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: Binding has not yet been initialized.
E/flutter (21626): The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
E/flutter (21626): Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
E/flutter (21626): In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
根据提示,我们在main函数顶部添加 WidgetsFlutterBinding.ensureInitialized(); 先进行flutter底层的相关绑定。
代码如下:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await LocalStorage.init();
runApp(const MyApp());
}
注: 这个问题在web环境下没有问题,在设备上会出现。