如何针对单个索引来执行特定功能

问题描述 投票:0回答:1

我试图针对特定索引来执行(发送/拒绝/确认)功能,但不幸的是,当我按下单个按钮时,功能适用于所有按钮。我应该怎么做才能解决这个问题?请帮我。我被困了好几天了。When I click on single buttonAll have changed

我制作了一个模型并获取了一个唯一的 id,但所有逻辑都让我陷入困境,任何人都可以用简单的方式描述这个逻辑吗? 我提供了调用该函数的主要代码。

                @override
                Widget build(BuildContext context){
                return Scaffold(
                 appBar: AppBar(
                 backgroundColor: mainColor,
                 title: Text("Choose Your Partner")),
                 body: SafeArea( 
                 child: SingleChildScrollView( 
                 child: Column( 
                 children: [ 
                 Padding( 
                 padding: const EdgeInsets.all(8.0), 
                 child: StreamBuilder( 
                 stream: FirebaseFirestore.instance.collection('recentPublished') .snapshots(),
                 builder: (context, snapshot) {
                 userId = FirebaseAuth.instance.currentUser.uid;
                 ListOfIndex list = ListOfIndex(snapshot);
                if (!snapshot.hasData) {
                  return Center(
                      child: const CupertinoActivityIndicator());
                } else {
                  return ListView.builder(
                    shrinkWrap: true,
                    primary: false,
                    itemCount: snapshot.data.docs.length,
                    itemBuilder: (context, index) {
                      return Column(
                        children: [
                          _vehicleCard(
                              userId,
                              snapshot.data.docs[index]["userId"]
                                  .toString(),
                              snapshot.data.docs[index]["riderProfileUrl"]
                                  .toString(),
                              userName,
                              snapshot.data.docs[index]["rideOfferBy"]
                                  .toString(),
                              snapshot.data.docs[index]["travellingDate"]
                                  .toString(),
                              snapshot.data.docs[index]["pickUpPlace"]
                                  .toString(),
                              snapshot.data.docs[index]["destination"]
                                  .toString(),
                              snapshot.data.docs[index]["vehicleNumber"]
                                  .toString(),
                              snapshot
                                  .data.docs[index]["vehicleName&Models"]
                                  .toString(),
                              snapshot.data.docs[index]["vehicleColor"]
                                  .toString(),
                              snapshot.data.docs[index]["seat"]
                                  .toString(),
                              snapshot.data.docs[index]["fairPrice"]
                                  .toString(),
                              snapshot.data.docs[index]["fcmToken"]
                                  .toString()),

                          (pending == false) ?
                           ElevatedButton(
                            onPressed: () async {

                              if(snapshot.data.docs[index]["fcmToken"] == "upcoming")
                                {
                                  pending = true;
                                  setState(() {

                                  });
                                }

                                try {
                                  final body = {
                                    "to": snapshot.data.docs[index]["fcmToken"]
                                        .toString(),
                                    "notification": {
                                      "title": snapshot.data.docs[index]["rideOfferBy"]
                                          .toString(),
                                      "body":
                                      "Are you ready for this ride?",
                                      "android_channel_id":
                                      "Vision DG Tech"
                                    },
                                    'data': {'type': 'notify',
                                      'status': 'pending'
                                    }
                                  };
                                  var res = await post(
                                    Uri.parse(
                                        'https://fcm.googleapis.com/fcm/send'),
                                    body: jsonEncode(body),
                                    headers: {
                                      HttpHeaders.contentTypeHeader:
                                      'application/json; charset=UTF-8',
                                      HttpHeaders
                                          .authorizationHeader:
                                      "key=$key"
                                    },
                                  );
                                  pending = true;
                                  setState(() {});
                                  print('Res -------- ${res.body}');
                                } catch (_) {}

                            },


                            child: Text(
                      (pending == false)?"Send Request":"Pending...",
                      ),
                            style: ButtonStyle(
                                backgroundColor: MaterialStatePropertyAll(
                                    pSecondaryColor)),
                          ) : TextButton(onPressed: (){}, child: Text("Pending..."))

                        ],
                      );
                    },
                  );
                }
              }),
        )
      ],
    ),
  ),
),
);
flutter dart listviewitem flutter-listview
1个回答
0
投票

您对许多列表项使用单个变量。

您必须单独定位每个列表项。

为此,您必须创建一个列表,其中每个项目

pending
都是
false

试试这个代码

 @override
            Widget build(BuildContext context){
            return Scaffold(
             appBar: AppBar(
             backgroundColor: mainColor,
             title: Text("Choose Your Partner")),
             body: SafeArea( 
             child: SingleChildScrollView( 
             child: Column( 
             children: [ 
             Padding( 
             padding: const EdgeInsets.all(8.0), 
             child: StreamBuilder( 
             stream: FirebaseFirestore.instance.collection('recentPublished') .snapshots(),
             builder: (context, snapshot) {
             userId = FirebaseAuth.instance.currentUser.uid;
             ListOfIndex list = ListOfIndex(snapshot);
            if (!snapshot.hasData) {
              return Center(
                  child: const CupertinoActivityIndicator());
            } else {
              return ListView.builder(
                shrinkWrap: true,
                primary: false,
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context, index) {
                List pendingList = List.generate(snapshot.data.docs.length, 
                 (index)=> false);
                  return Column(
                    children: [
                      _vehicleCard(
                          userId,
                          snapshot.data.docs[index]["userId"]
                              .toString(),
                          snapshot.data.docs[index]["riderProfileUrl"]
                              .toString(),
                          userName,
                          snapshot.data.docs[index]["rideOfferBy"]
                              .toString(),
                          snapshot.data.docs[index]["travellingDate"]
                              .toString(),
                          snapshot.data.docs[index]["pickUpPlace"]
                              .toString(),
                          snapshot.data.docs[index]["destination"]
                              .toString(),
                          snapshot.data.docs[index]["vehicleNumber"]
                              .toString(),
                          snapshot
                              .data.docs[index]["vehicleName&Models"]
                              .toString(),
                          snapshot.data.docs[index]["vehicleColor"]
                              .toString(),
                          snapshot.data.docs[index]["seat"]
                              .toString(),
                          snapshot.data.docs[index]["fairPrice"]
                              .toString(),
                          snapshot.data.docs[index]["fcmToken"]
                              .toString()),

                      (pendingList[index] == false) ?
                       ElevatedButton(
                        onPressed: () async {

                          if(snapshot.data.docs[index]["fcmToken"] == "upcoming")
                            {
                              pendingList[index] = true;
                              setState(() {

                              });
                            }

                            try {
                              final body = {
                                "to": snapshot.data.docs[index]["fcmToken"]
                                    .toString(),
                                "notification": {
                                  "title": snapshot.data.docs[index]["rideOfferBy"]
                                      .toString(),
                                  "body":
                                  "Are you ready for this ride?",
                                  "android_channel_id":
                                  "Vision DG Tech"
                                },
                                'data': {'type': 'notify',
                                  'status': 'pending'
                                }
                              };
                              var res = await post(
                                Uri.parse(
                                    'https://fcm.googleapis.com/fcm/send'),
                                body: jsonEncode(body),
                                headers: {
                                  HttpHeaders.contentTypeHeader:
                                  'application/json; charset=UTF-8',
                                  HttpHeaders
                                      .authorizationHeader:
                                  "key=$key"
                                },
                              );
                              pendingList[index] = true;
                              setState(() {});
                              print('Res -------- ${res.body}');
                            } catch (_) {}

                        },


                        child: Text(
                  (pendingList[index] == false)?"Send Request":"Pending...",
                  ),
                        style: ButtonStyle(
                            backgroundColor: MaterialStatePropertyAll(
                                pSecondaryColor)),
                      ) : TextButton(onPressed: (){}, child: Text("Pending..."))

                    ],
                  );
                },
              );
            }
          }),
© www.soinside.com 2019 - 2024. All rights reserved.