flutter setstate改变了所有处于抖动状态的项

tkclm6bt  于 2023-04-13  发布在  Flutter
关注(0)|答案(2)|浏览(139)

我有一个问题,当我点击一个产品按钮时,我的代码工作正常,但当我点击另一个按钮时,它会混淆,所以基本上当我点击一个产品时,它会按照我想要的方式更改按钮,但当我点击另一个按钮时,它会更改第一个按钮的状态,我知道这个错误是因为isCarted变量被设置为false或true,但我不知道如何解决它,这是我的代码:

import 'dart:ffi';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import 'package:groccer_app/Drawer/categories/prodetails.dart';
import 'package:add_to_cart_animation/add_to_cart_animation.dart';

class Products extends StatefulWidget {
  final String imgUrl;
  final String title;
  final String quantity;
  final String prodetail;
  final String price;
  final Function ontap;
  final String docId;
  // final bool carted;
  const Products(
      {super.key,
      required this.imgUrl,
      required this.title,
      required this.quantity,
      required this.price,
      required this.prodetail,
      required this.ontap,
      // required this.carted,
      required this.docId});

  @override
  State<Products> createState() => _ProductsState();
}

class _ProductsState extends State<Products> {
  bool isCarted = false;
  getdata() async {
    if (FirebaseAuth.instance.currentUser != null) {
      FirebaseFirestore.instance
          .collection('Admin')
          .doc('products')
          .collection('IsCarted')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .collection("UserData")
          .get()
          .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
          if (doc["CartedDoc"] == widget.docId) {
            setState(() {
              isCarted = true;
            });
          } else {
            setState(() {
              isCarted = false;
            });
          }
          // print(doc["CartedDoc"] == widget.docId);
        });
      });
      // print(isCarted.toString() + "carted");
    }
  }

  @override
  Widget build(BuildContext context) {
    getdata();
    return Container(
      // height: MediaQuery.of(context).size.height,
      child: widget.imgUrl != "" &&
              widget.price != "" &&
              widget.title != "" &&
              widget.prodetail != "" &&
              widget.quantity != ""
          ? Column(children: [
              GestureDetector(
                onTap: () {
                  // print("dd");
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => productDetails(
                                detail: widget.prodetail,
                                imageUrl: widget.imgUrl,
                                price: widget.price,
                                title: widget.title,
                                quantity: widget.quantity,
                              )));
                  setState(() {
                    // categoriesList[index]['isExpanded'] = !isExpanded;
                    // categoriesList[index]['icon'] = isExpanded
                    //     ? Icons.keyboard_arrow_down_rounded
                    //     : Icons.keyboard_arrow_up_rounded;
                  });
                },
                child: Card(
                  child: Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Row(
                      children: [
                        Container(
                          // key: widgetKey,
                          width: 60,
                          height: 60,
                          color: Colors.transparent,
                          child: Image.network(
                            widget.imgUrl,
                            // width: 100,
                            // height: 100,
                          ),
                        ), // widget to be displayed inside the avatar
                        // Image.asset(
                        //   category['imagePath'],
                        //   width: 150,
                        // ),
                        const SizedBox(width: 16.0),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                width: MediaQuery.of(context).size.width,
                                child: Text(widget.title,
                                    // "Onion - Pyaz",
                                    // style: const TextStyle(
                                    //   fontWeight: FontWeight.bold,
                                    // ),
                                    style: const TextStyle(
                                        fontWeight: FontWeight.w500,
                                        fontSize: 15)),
                              ),
                              const SizedBox(height: 7.0),
                              Text(
                                widget.quantity,
                                style: const TextStyle(
                                    overflow: TextOverflow.ellipsis,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w400,
                                    color: Color.fromRGBO(146, 146, 146, 1.0)),
                              ),
                              const SizedBox(height: 50.0),
                              Text("Rs: " + widget.price,
                                  style: const TextStyle(
                                      fontWeight: FontWeight.w800,
                                      fontSize: 17,
                                      color: Color.fromRGBO(230, 0, 57, 1.0))),
                            ],
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            const SizedBox(
                              height: 40,
                            ),
                            const Icon(
                              Icons.arrow_forward_ios_rounded,
                              // category['icon'],
                              color: Color.fromRGBO(193, 193, 193, 1.0),
                            ),
                            const SizedBox(
                              height: 30,
                            ),
                            isCarted == false
                                ? ElevatedButton(
                                    //           onPressed: () async {
                                    //             CollectionReference collref =
                                    //     await FirebaseFirestore.instance
                                    //         .collection('Admin')
                                    //         .doc('products')
                                    //         .collection('IsCarted')
                                    //         .doc(FirebaseAuth.instance.currentUser!.uid)
                                    //         .collection("UserData");
                                    // await collref.add({
                                    //   "CartedDoc": widget.docId,
                                    // });
                                    //             // widget.ontap();
                                    //             print("this" + isCarted.toString());
                                    //           },
                                    onPressed: () async {
                                      CollectionReference collref =
                                          await FirebaseFirestore.instance
                                              .collection('Admin')
                                              .doc('products')
                                              .collection('IsCarted')
                                              .doc(FirebaseAuth
                                                  .instance.currentUser!.uid)
                                              .collection("UserData");

                                      // Add the document to the collection and wait for the operation to complete
                                      await collref
                                          .add({"CartedDoc": widget.docId});

                                      // Update the state and print the value of `isCarted`
                                      setState(() {
                                        isCarted = true;
                                        print("this " + isCarted.toString());
                                      });
                                    },

                                    child: const Text(
                                      "Add to Cart",
                                      style: TextStyle(
                                          color: Color.fromRGBO(
                                              191, 232, 203, 1.0)),
                                    ),
                                    style: ElevatedButton.styleFrom(
                                        backgroundColor: const Color.fromRGBO(
                                            25, 174, 68, 1.0),
                                        elevation: 0),
                                  )
                                : ElevatedButton(
                                    onPressed: () async {
                                      //                   CollectionReference collref =
                                      //     await FirebaseFirestore.instance
                                      //         .collection('Admin')
                                      //         .doc('products')
                                      //         .collection('IsCarted')
                                      //         .doc(FirebaseAuth.instance.currentUser!.uid)
                                      //         .collection("UserData");
                                      // await collref.add({
                                      //   "CartedDoc": doc.id,
                                      // });
                                      if (FirebaseAuth.instance.currentUser !=
                                          null) {
                                        CollectionReference collref =
                                            await FirebaseFirestore.instance
                                                .collection('Admin')
                                                .doc('products')
                                                .collection('IsCarted')
                                                .doc(FirebaseAuth
                                                    .instance.currentUser!.uid)
                                                .collection("UserData");
                                        collref.get().then(
                                            (QuerySnapshot querySnapshot) {
                                          querySnapshot.docs
                                              .forEach((doc) async {
                                            // if (doc["CartedDoc"] == widget.docId) {
                                            //   setState(() {
                                            //     isCarted = true;
                                            //   });
                                            // } else {
                                            //   isCarted = false;
                                            // }
                                            await doc.reference.delete();
                                            // print(doc["CartedDoc"] == widget.docId);
                                          });
                                        });
                                      }
                                      setState(() {
                                        isCarted = false;
                                        print("this " + isCarted.toString());
                                      });
                                      // getdata();
                                    },
                                    style: ButtonStyle(
                                        backgroundColor:
                                            MaterialStateColor.resolveWith(
                                                (states) => Colors.white),
                                        elevation:
                                            MaterialStateProperty.resolveWith(
                                                (states) => 0),
                                        side: MaterialStateProperty.resolveWith<
                                            BorderSide>(
                                          (Set<MaterialState> states) {
                                            // if (states.contains(MaterialState.disabled)) {
                                            //   // return null;
                                            // }
                                            return BorderSide(
                                                color: Color.fromRGBO(
                                                    25, 174, 68, 1.0),
                                                width:
                                                    3); // set border color here
                                          },
                                        )),
                                    // onPressed: () async {
                                    //   widget.ontap();
                                    //   print("this" + isCarted.toString());
                                    // },
                                    // child: const Text(
                                    //   "Added to Cart",
                                    //   style: TextStyle(
                                    //       color: Color.fromRGBO(
                                    //           191, 232, 203, 1.0)),
                                    // ),
                                    child: Row(
                                      children: [
                                        Icon(
                                          Icons.delete,
                                          color: Colors.black,
                                        ),
                                      ],
                                    ),

                                    //   style: ElevatedButton.styleFrom(
                                    //       backgroundColor: Colors.white,

                                    // )
                                  )
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              )
            ])
          : Container(),
    );
  }
}
x6492ojm

x6492ojm1#

是否应该总是在构建方法中调用GetData()?
不要在构建方法中调用setState。

@override
Widget build(BuildContext context) {
       getdata();
       return Container(....

使用FutureBuilder。

@override
Widget build(BuildContext context) {
       return FutureBuilder(
              future: getdata(),
              builder: (context, snapshot) {
                 return Container(....

祝你有一个美好的编码生活:)

rjee0c15

rjee0c152#

看看这个问题和它的答案。我相信它会有所帮助:
Flutter 设置状态仅重建一个子级

相关问题