首页 > 解决方案 > 必须初始化不可为空的变量“_preferences”。尝试添加初始化表达式

问题描述

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

标签: flutterdart-null-safetyflutter-sharedpreference

解决方案


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

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

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

static SharedPreferences _preferences = SharedPreferences.getInstance();

当您调用此属性时,您可以在该页面上使用async/await_preferences属性。


推荐阅读