这是整个代码文件
在 getInstance()
上运行 SharedPreferences
时,它会抛出“用于空值的空检查运算符”错误。但在 initState
getInstance
时有效
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
main(List<String> args) {
runApp(MaterialApp(home: MyApp()));
}
// ignore: must_be_immutable
class MyApp extends StatefulWidget {
SharedPreferences sharedPreferences;
MyApp() {
SharedPreferences.getInstance().then((value) {
sharedPreferences = value;
});
}
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text(
"${(widget.sharedPreferences != null) ?
widget.sharedPreferences.getInt('count') ?? 'no count found' : ''}",
),
ElevatedButton(
onPressed: () => setState(() {}),
child: Text("setState"),
),
],
),
));
}
}
为什么会这样?