共享首选项插件(shared_preferences: ^2.0.6)
它有一个初始化实例错误,这是错误堆栈跟踪:
aunching lib/main.dart on iPhone 12 Pro Max in debug mode...
package:travel_app/main.dart:1
Xcode build done. 22.3s
Connecting to VM Service at ws://127.0.0.1:59168/kc8UwLPVK5s=/ws
flutter: start
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
#0 MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:142
#1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:148
#2 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:331
#3 MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
#4 MethodChannelSharedPreferencesStore.getAll
package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44
#5 SharedPreferences._getSharedPreferencesMap
package:shared_preferences/shared_preferences.dart:180
#6 SharedPreferences.getInstance
package:shared_preferences/shared_preferences.dart:56
#7 Global.init
package:travel_app/common/Global.dart:36
#8 main
package:travel_app/main.dart:13
#9 _runMainZoned.<anonymous closure>.<anonymous closure> (d<…>
这是我的代码(main.dart):
Future<void> main() async => await Global.init().then((e) => runApp(MyApp()));
全局.dart
static Future init() async {
print("start");
final SharedPreferences prefs = await
SharedPreferences.getInstance();
print("_prefs $prefs");
}
源代码定位器错误如下:(method_channel_shared_preferences.dart)
await _kChannel.invokeMapMethod<String, Object>('getAll');
发生异常。 _CastError(用于空值的空检查运算符)
否则,我使用的系统是MacOS,有谁知道如何解决这个问题?
答案 0 :(得分:3)
在初始化之前执行WidgetsFlutterBinding.ensureInitialized();
答案 1 :(得分:0)
任何使用 get_it 包并遇到类似问题的人,这里是最简单的解决方案。 只需在主函数顶部添加 WidgetsFlutterBinding.ensureInitialized();。
像这样改变你的主要功能:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init()
runApp(MyApp());}