我是新手,并尝试将Firebase包与以下代码行结合使用。
我真的很想知道这行代码的实际作用吗?
官方文档对我没有太大帮助。有人可以解释一下吗?
最佳答案
您必须以这种方式使用它:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
https://flutter.dev/docs/resources/architectural-overview#architectural-layers
上图是Flutter的体系结构层,
WidgetFlutterBinding
用于与Flutter引擎进行交互。 Firebase.initializeApp()
需要调用本地代码来初始化Firebase,并且由于插件需要使用平台通道来调用本地代码,这是异步完成的,因此您必须调用ensureInitialized()
来确保您拥有WidgetsBinding
的实例。从docs:
从source code:
@override
Future<FirebaseAppPlatform> initializeApp(
{String name, FirebaseOptions options}) async {
if (name == defaultFirebaseAppName) {
throw noDefaultAppInitialization();
}
// Ensure that core has been initialized on the first usage of
// initializeApp
if (!isCoreInitialized) {
await _initializeCore();
}
// If no name is provided, attempt to get the default Firebase app instance.
// If no instance is available, the user has not set up Firebase correctly for
// their platform.
if (name == null) {
MethodChannelFirebaseApp defaultApp =
appInstances[defaultFirebaseAppName];
if (defaultApp == null) {
throw coreNotInitialized();
}
return appInstances[defaultFirebaseAppName];
}
assert(options != null,
"FirebaseOptions cannot be null when creating a secondary Firebase app.");
// Check whether the app has already been initialized
if (appInstances.containsKey(name)) {
throw duplicateApp(name);
}
_initializeFirebaseAppFromMap(await channel.invokeMapMethod(
'Firebase#initializeApp',
<String, dynamic>{'appName': name, 'options': options.asMap},
));
return appInstances[name];
}
invokeMapMethod
将使用指定的参数在上述通道上调用一个方法,然后将在本机代码中调用initializeApp()
方法,https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_core/firebase_core/android/src/main/java/io/flutter/plugins/firebase/core/FlutterFirebaseCorePlugin.java#L227
还有多种初始化Firebase的方法,您可以在此处检查:
No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase
在其他方式中,我们不调用
WidgetsFlutterBinding.ensureInitialized()
,因为runApp()
函数在内部对其进行了调用:void runApp(Widget app) {
WidgetsFlutterBinding.ensureInitialized()
..scheduleAttachRootWidget(app)
..scheduleWarmUpFrame();
}
https://github.com/flutter/flutter/blob/bbfbf1770c/packages/flutter/lib/src/widgets/binding.dart#L1012关于firebase - WidgetsFlutterBinding.ensureInitialized()有什么作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63873338/