flutter - 必须初始化不可为空的变量“_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.
解决方案
当您在方法中创建如下变量时,您必须创建一个对象:
static Future init() async {
SharedPreferences _preferences = await SharedPreferences.getInstance();
}
对于使用类似的属性,你可以这样做:
static SharedPreferences _preferences = SharedPreferences.getInstance();
当您调用此属性时,您可以在该页面上使用async/await
此_preferences
属性。
推荐阅读
- android - 您上传了以调试模式登录的 APK 或 Android App Bundle
- go - 如何为 REST 服务生成代码覆盖率
- mysql - 从数据库更新模型 | 视觉工作室 2019
- android - TWA android 应用程序错误:android.support.customtabs.CustomTabColorSchemeParams.toBundle()' 无法访问
- cadence-workflow - 优先级如何在节奏工作流程中发挥作用?
- python - 当函数用作参数时,try-block 不起作用
- javascript - react.js - react-alert - 未捕获的不变违规:无效的挂钩调用
- python - 如何从pdf中提取带有缩进的文本?
- c++ - 为什么不同的向量
元素共享相同的地址? - node.js - 响应中缺少 GraphQL 突变类型