这是整个代码文件,在它上面运行getInstance()
时SharedPreferences
会抛出“Null check operator used on a null value”错误。但getInstance
在 initState 中调用时有效
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"),
),
],
),
));
}
}
为什么会这样?