设置状态改变颤振中的所有项



我有一个问题,当我点击一个产品按钮时,我的代码工作得很好,但当我点击另一个产品时,它混淆了,所以基本上当我点击一个产品时,它改变了我想要的按钮但当我点击另一个时,它改变了第一个的状态,这一切都混淆了。我知道错误是由于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(),
);
}
}

应该总是在构建方法中调用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(....

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

看看这个问题和答案。我相信它会有帮助的:

flutter setstate rebuild only one child

相关内容

  • 没有找到相关文章

最新更新