I have a problem that my code is working fine when I tap on one product button, but when I tap on the other one it mixes up, So basically when I tap on the one product it changes the button as I want but when I tap another one it changes the state of first one, this all mix up is happening. I know that the error is causing because of isCarted variable is set to false or true but I don’t know how to solve it here is my code:
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(),
);
}
}
2
Answers
Should you always call GetData() inside the build method?
Don’t call setState in build methods.
use FutureBuilder.
Have a nice coding life. 🙂
Check out this quetions and the the answers to it. I belive it will help out:
flutter setstate rebuild only one child