按下图标后图标未更改-颤振

时间:2020-09-21 09:16:24

标签: flutter icons favorites

我正在创建收藏页面。对于每个产品页面,我在应用程序栏上放置了一个收藏夹图标,该图标旨在更改并将特定产品添加到用户的收藏夹中。

按下图标后,我无法更改其状态。

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); 
                        }
                      });}

1 个答案:

答案 0 :(得分:1)

您的状态不会改变,因为您将它们放入build方法中,该方法始终会对其进行初始化。

将状态_savedalreadySaved放在build方法之外。

  final _saved = Set<BuildContext>();
  final alreadySaved = _saved.contains(context);

  @override
  Widget build(BuildContext context) {

  }