必须初始化不可为 null 的变量“_preferences”。尝试添加初始化表达式

The non-nullable variable '_preferences' must be initialized. Try adding an initializer expression

我正在尝试实现一个 class,我可以在其中调用 SharedPreferences 函数。

import 'package:shared_preferences/shared_preferences.dart';


class UserPreferences {
  static SharedPreferences _preferences;

  static const _keyToken = 'token';

  static Future init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  static Future setToken(String token) async =>
    await _preferences.setString(_keyToken, token);

  static String getToken() => _preferences.getString(_keyToken);

}

但我收到以下错误:

The non-nullable variable '_preferences' must be initialized.
Try adding an initializer expression.

在方法中创建变量时必须创建一个对象,如下所示:

  static Future init() async {
    SharedPreferences _preferences = await SharedPreferences.getInstance();
  }

要像 属性 那样使用,您可以按如下方式进行:

static SharedPreferences _preferences = SharedPreferences.getInstance();

当您调用此 属性 时,您可以在该页面上将 async/await 用于此 _preferences 属性。

理解问题

The non-nullable variable '_preferences' must be initialized.

有了 NULL 安全机制,您就不能再让 Non-Nullable 类型处于未初始化状态。

 static SharedPreferences _preferences;

这里你还没有初始化不可为空的SharedPreferences


解决方案

1.初始化它

 static Future init() async {
    SharedPreferences _preferences = await SharedPreferences.getInstance() as SharedPreferences;;
  }

2。使其可空

NOTE : This solution will work but is not recommended as you are making it nullable which means it can hold null (can cause crashes in future program flow).

添加 ? 使其成为“NULLABLE”

 static SharedPreferences? _preferences;

late添加到_preferences的声明中,像这样:

static late SharedPreferences _preferences;

最终代码:

import 'package:shared_preferences/shared_preferences.dart';

class UserPreferences {
  static late SharedPreferences _preferences;

  static const _keyToken = 'token';

  static Future init() async {
    _preferences = await SharedPreferences.getInstance();
  }

  static Future setToken(String token) async =>
      await _preferences.setString(_keyToken, token);

  static String getToken() => _preferences.getString(_keyToken);
}