【问题标题】:The non-nullable variable '_preferences' must be initialized. Try adding an initializer expression必须初始化不可为空的变量“_preferences”。尝试添加初始化表达式
【发布时间】:2026-01-12 14:15:02
【问题描述】:

我正在尝试实现一个可以调用 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.

【问题讨论】:

    标签: flutter dart-null-safety flutter-sharedpreference


    【解决方案1】:

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

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

    对于使用类似的属性,你可以像下面这样:

    static SharedPreferences _preferences = SharedPreferences.getInstance();
    

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

    【讨论】:

    • 但是如果没有异步,等待是行不通的,我怎么能放异步
    • static SharedPreferences _preferences = SharedPreferences.getInstance() as SharedPreferences; 这行有效。谢谢!
    【解决方案2】:

    理解问题

    必须初始化不可为空的变量“_preferences”。

    有了 NULL 安全性,您不能再让 Non-Nullable 类型未初始化。

     static SharedPreferences _preferences;
    

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


    解决方案

    1.初始化它

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

    2。使其可空

    注意:此解决方案可以工作,但不推荐使用,因为您将其设为可空,这意味着它可以容纳 null(可能导致未来程序流崩溃)。

    添加? 使其为“NULLABLE”

     static SharedPreferences? _preferences;
    

    【讨论】:

    • 最初我在写这个答案的时候还以为是,后来发现你用的是my formatting signature,哈哈。
    • @CopsOnRoad 哈哈哈.....但巧合的是,即使我想出了这种格式。我今天知道你也遵循这种格式:)
    • 我使用这种格式已经快一年了,你还没有看到我这样写的任何答案(作为 Flutter 开发人员)有点奇怪!
    • @CopsOnRoad 是的,伙计!上个月你是不是有点不活跃。因为我的大部分答案都是上个月发布的,没有看到你的任何答案
    • 好吧,我现在并没有真正检查所有“新发布的问题”,尽管几年前我曾经这样做过。无论如何,我已经在 SO 上发布了将近 3 年的答案,而且我的大部分答案(我相信几乎所有活跃于“Flutter”的人)都必须看过它们(可能包括你,哈哈)。所以,我的格式实际上是~2-3岁。这是一个未经编辑的旧post
    最近更新 更多