我正在创建收藏页面。对于每个产品页面,我在应用程序栏上放置了一个收藏夹图标,该图标旨在更改并将特定产品添加到用户的收藏夹中。
按下图标后,我无法更改其状态。
class FoodDetail extends StatefulWidget {
@override
_FoodDetail createState()=> _FoodDetail();
const FoodDetail({Key key}) : super(key: key);
}
class _FoodDetail extends State<FoodDetail>{
@override
Widget build(BuildContext context) {
FoodNotifier foodNotifier = Provider.of<FoodNotifier>(context);
_onFoodDeleted(Food food) {
Navigator.pop(context);
foodNotifier.deleteFood(food);
}
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
return Scaffold(
appBar: AppBar(
title: Text(foodNotifier.currentFood.name),
actions: <Widget>[
// action button
new IconButton(
icon: alreadySaved ? Icon(Icons.star) : Icon(Icons.star_border),
color: alreadySaved ? Colors.yellow[500] : null,
onPressed: (){
setState(() {
if (alreadySaved) {
_saved.remove(context);
} else {
_saved.add(context);
}
});}
答案 0 :(得分:1)
您的状态不会改变,因为您将它们放入build
方法中,该方法始终会对其进行初始化。
将状态_saved
,alreadySaved
放在build
方法之外。
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
@override
Widget build(BuildContext context) {
}