SharedPreferences.getInstance() 正在抛出 _CastError(空值检查运算符用于空值)

Posted

技术标签:

【中文标题】SharedPreferences.getInstance() 正在抛出 _CastError(空值检查运算符用于空值)【英文标题】:SharedPreferences.getInstance() is throwing _CastError (Null check operator used on a null value) 【发布时间】:2021-10-22 20:29:13 【问题描述】:

我是 Flutter 的新手,还在学习。我正在尝试获取 SharedPreferences 实例的引用,但出现以下错误

_CastError(用于空值的空检查运算符)

这就是我的代码的样子

app_settings.dart

class AppSettings 
  
  final SharedPreferences _pref;
  
  AppSettings._(this._pref);

  static AppSettings? _instance;

  static initialize() async 
    if (_instance != null) 
      // already initialized
      return;
    
    // instance not found. creating one
   
    var pref = await SharedPreferences.getInstance();
    _instance = AppSettings._(pref);

  

main.dart

Future<void> main() async 
  // initializing application settings
  await AppSettings.initialize();
  runApp(App());


class App extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
        title: "hello app",
        home: AppHome());
  

经过进一步调试,我发现异常是由 invokeMapMethod in

引发的

flutter-sdk/flutter/packages/flutter/lib/src/services/platform_channel.dart

getAll方法调用

flutter-sdk/flutter/.pub-cache/hosted/pub.dartlang.org/shared_preferences_platform_interface-2.0.0/lib/method_channel_shared_preferences.dart

以下是错误截图

【问题讨论】:

你用的是哪个版本的flutter和shared_preferences? Flutter 2.2.3,shared_preferences:^2.0.6 和 dart 2.13.4 【参考方案1】:

我在runApp() 之前打电话给SharedPreferences.getInstance()。由于SharedPreferences 使用的特定于平台的本机绑定未初始化,因此它抛出了一个空异常。所以我在调用await SharedPreferences.getInstance()之前添加了WidgetsFlutterBinding.ensureInitialized()

Future<void> main() async 
  // initializing application settings
  WidgetsFlutterBinding.ensureInitialized();
  await AppSettingService.initialize();
  runApp(WorkoutTrackerApp());

您可以通过以下链接了解更多信息

SharedPreferences error in Flutter What Does WidgetsFlutterBinding.ensureInitialized() do? ensureInitialized method documentation

【讨论】:

【参考方案2】:

怎么样

static initialize async() 
  _instance = _instance?AppSettings(await SharedPreferences.getInstance());

【讨论】:

【参考方案3】:

试试:

if (preferences == null) return  as Map;

【讨论】:

以上是关于SharedPreferences.getInstance() 正在抛出 _CastError(空值检查运算符用于空值)的主要内容,如果未能解决你的问题,请参考以下文章