flutter - GetInt 在 null 上被调用
问题描述
我在颤振中对 sharedPreferences 做错了什么吗?
SharedPreferences prefs;
int score;
int storedScore;
final String uid;
StoredData(this.uid) {
_initialize();
_readValues();
}
_initialize() async {
prefs = await SharedPreferences.getInstance();}
_readValues() {
score = prefs.getInt("score") ?? 0;
storedScore = prefs.getInt("storedScore") ?? 0;}
错误:I/flutter (18698):在 null 上调用了方法“getInt”。I/flutter (18698): Receiver: null I/flutter (18698): 尝试调用: getInt("score") 相关的导致错误的小部件是: I/flutter (18698): HomeScreen file:///D:/颤振/trivia_iq/trivia_iq/lib/main.dart:24:33
这不在 main.dart 文件中,但我得到了这个。任何帮助将不胜感激。
解决方案
在“StoredData()”构造函数中,您也应该在调用“_initialize()”方法时使用 await:
await _initialize();
如果不是,“_readValues()”将在 sharedPreferences 尚未初始化时被调用。
但是由于不允许在构造函数上使用异步,您应该像这样更改 initialize():
_initialize() async {
prefs = await SharedPreferences.getInstance();
score = prefs.getInt("score") ?? 0;
storedScore = prefs.getInt("storedScore") ?? 0;
}
在您的小部件中,您可以执行以下操作:
class MyWidget extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
home: FutureBuilder(
future: StoredData._initialize(),
builder: (_,snap){
if (snap.connectionState==ConnectionState.done)
return Text("Settings loaded");
else
return Text("Loading settings...");
}
),);
}
}
class StoredData {
static SharedPreferences _prefs;
static int score;
static int storedScore;
final String uid;
StoredData(this.uid);
static Future _initialize() async {
_prefs = await SharedPreferences.getInstance();
score = _prefs.getInt("score") ?? 0;
storedScore = _prefs.getInt("storedScore") ?? 0;
}
}