首页 > 解决方案 > 用最喜欢的按钮颤动 Firestore 项目。当我按下某个项目的收藏按钮时,它会使所有其他项目按钮也变为红色

问题描述

截屏

我想按下最喜欢的项目来切换它的最爱,而不是所有其他项目。我尝试了一切,但没有任何解决方案。我试图创建一个有状态的小部件并将那段代码放入其中,但它不起作用。我没有任何解决方案。我应该怎么做才能将特定项目的按钮变为红色?

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

有人有解决方案吗?

标签: firebaseflutter

解决方案


您正在使用公共变量favorite_color将颜色应用于列表中的所有项目。相反,您应该为所有项目设置唯一变量。

创建一个 <String, Color> 类型的 Map 并用你的项目的颜色填充它

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

推荐阅读