简体   繁体   English

Flutter 带有收藏按钮的 Firestore 项目。 当我按下某个项目的收藏按钮时,它会使所有其他项目按钮也变为红色

[英]Flutter firestore items with favorite button. when i press the favorite button for an item it makes all the other items button to red also

Screenshot截屏

I want to press on the item favourite to toggle its favourite only not all the other items.我想按下最喜欢的项目来切换它的最爱,而不是所有其他项目。 I tried everything and I don't have any solution.我尝试了一切,但没有任何解决方案。 I tried to create a stateful widget and put that piece of code into it but it didn't work.我试图创建一个有状态的小部件并将那段代码放入其中,但它不起作用。 I don't have any solutions.我没有任何解决方案。 What should I do to turn a specific item's button red?我应该怎么做才能将特定项目的按钮变为红色?

Flexible(
            child:  StreamBuilder(
              stream: getRestaurantsbyAddress(context),
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                if (address==null || snapshot.data == null) {
                  return Center(
                    child: CircularProgressIndicator()
                  );
                }
                else if (snapshot.data.size==0) {
                  return Center(
                    child: Text("No restaurants found",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20,color: Colors.white),),
                  );
                }
                return ListView(
                  children: snapshot.data.docs.map((document)
                  {
                    return Padding(
                      padding: EdgeInsets.all(10),
                      child: Container(
                          width: 200,
                          height: 70,
                          decoration:  BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color: Colors.white,
                          ),
                          child: Row(
                            children: [
                              Padding(padding: EdgeInsets.only(left: 20),),
                              Text(document['name'],style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),
                              Align(
                                alignment: Alignment.centerRight,
                                child: ButtonBar(
                                  children: [
                                    IconButton(icon: Icon(Icons.call),highlightColor: Colors.red,iconSize: 30.0,onPressed:() async {
                                      var url ="tel:"+document['number'].toString();
                                      if (await canLaunch(url)) {
                                        await launch(url);
                                      } else {
                                        throw 'Could not launch $url';
                                      }
                                    }),
                                    IconButton(icon: Icon(Icons.location_on_rounded), iconSize: 30.0,onPressed:() async {
                                      var url =document['location'];
                                      if (await canLaunch(url)) {
                                        await launch(url);
                                      } else {
                                        throw 'Could not launch $url';
                                      }
                                    }),
                                    IconButton(
                                      icon: Icon(Icons.favorite),
                                      color: favorite_color,
                                      iconSize: 30,
                                      onPressed: () {
                                        setState(() {
                                          if (favorite_color==Colors.grey) {
                                            favorite_color=Colors.red;
                                            CollectionReference users = FirebaseFirestore.instance.collection("users");
                                            users.doc(phone).collection("usersFav").doc(document['name']+" "+document['address']).set(
                                                {
                                                  "name" : document['name'],
                                                  "number" : document['number'],
                                                  "address":document['address'],
                                                  "location":document['location'],
                                                }
                                            );
                                          }
                                          else if (favorite_color==Colors.red) {
                                            setState(() {
                                              favorite_color=Colors.grey;
                                              CollectionReference favorites = FirebaseFirestore.instance.collection("users");
                                              favorites.doc(phone).collection("usersFav").doc(document['name']+" "+document['address']).delete();
                                            });
                                          }
                                        });
                                      },
                                    ),
                                  ],
                                ) ,
                              )
                            ],
                          )
                      ),
                    );
                  }).toList(),
                );
              },
            )
        )

Does someone has a solution?有人有解决方案吗?

You are using the common variable favorite_color to apply color to all of your items in the list.您正在使用公共变量favorite_color将颜色应用于列表中的所有项目。 You should instead have unique variables for all the items.相反,您应该为所有项目设置唯一变量。

Create a Map of <String, Color> type and populate it with your item's colors创建一个 <String, Color> 类型的 Map 并用您的项目的 colors 填充它

Map<String, Color> favorite_colors = {};
(...)
@override
Widget build(BuildContext context) {
  ...
  return ListView(
    children: snapshot.data.docs.map((document)
    {
      //You should ideally fetch favorite status and assign the color accordingly
      Color favorite_color = favourite_colors[document['name']+" "+document['address']] ?? Colors.grey;
      // if the Map doesn't have any entry for this document then the default
      // color will be grey. You should therefore check if the item has already
      // been favorited using an async function and then give it a color
      (...)
      IconButton(
        icon: Icon(Icons.favorite),
        color: favorite_color,
        iconSize: 30,
        onPressed: () {
          setState(() {
            if (favorite_color==Colors.grey) {
              favourite_colors[document['name']+" "+document['address']] = Colors.red;
              ...
            } else {
              favourite_colors[document['name']+" "+document['address']] = Colors.grey;
            }
          });
        })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 需要您的支持:当我按下收藏按钮时,我想在我的 Flutter 数据库中获取产品 ID - Need your HELD : I want to get the product ID in my Flutter database when I press the favorite button Android firebase 收藏夹按钮更改 - Android firebase favorite button changes Cardview Android中的“收藏夹”按钮出错 - Error with favorite button in cardview Android 删除按钮 flutter Firestore - Delete button flutter Firestore 单击按钮时,Vue js 不会获取路由参数。 从 Firestore 更新用户 - Vue js don't get the route params when you click on button. Update user from firestore 在从 Firestore 添加和删除项目时切换收藏夹按钮 - Toggling a favorites button while adding and deleting items from firestore 每次按下按钮时数据都会翻倍 - Data doubles every time when i press the button 为什么当我在JSQMessagesViewController中按下发送按钮时出现2条消息 - Why do 2 messages appear when I press the send button in JSQMessagesViewController 当我按下“继续”按钮时应用程序崩溃(在活动之间转换) - App crashes when I press "continue" button (transitioning between activities) 有时当我按下按钮时它有时会不起作用 - sometimes when I press the button it works sometimes it doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM