我是不是在flutter中的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;}
error:Iflutter (18698): 在null.Iflutter(18698)上调用了'getInt'方法。接收器:nullIflutter (18698): 尝试调用:getInt("score")相关的致错部件是:Iflutter(18698):HomeScreen文件:/D:fluttertrivia_iqtrivia_iqlibmain.dart:24:33。
这不是在main.dart文件中,但我得到了这个。任何帮助将被感激。
这给出了null,因为共享偏好对象对象到现在还没有创建,而你正在某个地方使用它。
你必须添加Future,因为你确实在等待一些后台工作。
Future<Void> _initialize() async {
prefs = await SharedPreferences.getInstance();
}
调用函数一样。
_initialize().then((value) => _readValues());
在 "StoredData() "构造函数中 你应该在调用"_initialize() "方法时也使用 await:
await _initialize();
否则,当sharedPreferences尚未初始化时,"_readValues() "将被调用。
但是因为不允许在构造函数上使用async,你应该像这样修改initialize()。
_initialize() async {
prefs = await SharedPreferences.getInstance();
score = prefs.getInt("score") ?? 0;
storedScore = prefs.getInt("storedScore") ?? 0;
}
在你的widget中,你可以这样做。
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;
}
}
StoredData(this.uid) {
_initialize().then((value) => _readValues());
shouldStoreInFirebase();}
Future<void> _initialize() async {
prefs = await SharedPreferences.getInstance();}
_readValues() {
score = prefs.getInt("score") ?? 1;
storedScore = prefs.getInt("storedScore") ?? 0;
}