我创建了一个名为
isJoined
的 bool,当我想将它更改为形成 false
到 true
当我点击一个按钮时,但它给出了命名错误。我在共享首选项中存储isJoined
:
bool isJoined = false;
@override
void initState() {
_loadData();
super.initState();
}
_loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
isJoined = prefs.getBool('isJoined') ?? false; //the ?? false is a null checker//
});
}
// now I save it//
_savebool() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool("isJoined", isJoined);
}
但这就是问题发生的地方:
onPressed: () {isJoined = true, _savebool()},
//The argument type 'void Function()' can't be assigned
//to the parameter type 'void Function(BuildContext)?'
我试过在
?
中添加一个 bool
并在每个 isJoined
之后添加一个空检查器(!),但这不起作用。它给出了同样的错误。
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isJoined = false;
late SharedPreferences prefs;
@override
void initState() {
super.initState();
SharedPreferences.getInstance().then((value) {
setState(() {
prefs = value;
});
//load data
_loadData();
});
}
_loadData() async {
print("isJoined before setState: $isJoined");
bool storedIsJoined = prefs.getBool('isJoined') ?? false;
setState(() {
isJoined = storedIsJoined; //the ?? false is a null checker//
});
print("isJoined after setState: $isJoined");
}
// now I save it//
_savebool() async {
print("isJoined saving: $isJoined");
await prefs.setBool("isJoined", isJoined);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
await _savebool();
},
child: const Text("Go to next page"))
],
),
);
}
}