运行这个
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ThePage(),
);
}
}
class ThePage extends StatelessWidget {
const ThePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
);
}
}
给出用于空值的空检查运算符并指出行 Firebase.initializeApp()
。
我也试过 flutter clean
。
以及堆栈跟踪中的错误
E/flutter (31894): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (31894): #0 MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
E/flutter (31894): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
E/flutter (31894): #2 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
E/flutter (31894): #3 MethodChannel.invokeListMethod
package:flutter/…/services/platform_channel.dart:344
E/flutter (31894): #4 MethodChannelFirebase._initializeCore
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:30
E/flutter (31894): #5 MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:77
E/flutter (31894): #6 Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (31894): #7 main
package:firebasetests/main.dart:5
E/flutter (31894): #8 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (31894): #9 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (31894): #10 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (31894): #11 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (31894): #12 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (31894): #13 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (31894): #14 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (31894): #15 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
这是错误的堆栈跟踪,在主程序中删除 Firebase.initializeApp()
后,它运行良好。
答案 0 :(得分:5)
您应该在主函数中添加 WidgetsFlutterBinding.ensureInitialized();
:
void main() async {
WidgetsFlutterBinding.ensureInitialized(); // Add this
await Firebase.initializeApp();
runApp(MyApp());
}
对于 Firebase 初始化,需要使用 Flutter Platform Channels 访问本机代码。为此,您需要确保 Flutter 引擎绑定已初始化。
答案 1 :(得分:0)
使用@mkobuolys 提到的代码行。
我在 Visual Studio Code 中遇到了同样的问题,但它没有显示任何有关错误的详细信息,但 Android Studio 显示了。
如果有人感兴趣,这里是异常消息中最重要的信息:
<块引用>如果您正在运行应用程序并且需要访问二进制文件
已调用 runApp()
之前的信使(例如,在
插件初始化),那么你需要显式调用
WidgetsFlutterBinding.ensureInitialized()
首先。如果你正在运行一个
测试,您可以调用 TestWidgetsFlutterBinding.ensureInitialized()
作为测试的 main()
方法中的第一行来初始化
绑定。