I am building an e-commerce app using flutter and firebase. I am storing the cart data in a nested collection for each user in firestore and I want to show the number of items in cart above the cart icon in flutter but I don't know how to fetch that in real-time.
Here is the code of my homepage:
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
TabController _tabController;
@override
void initState() {
_tabController = TabController(length: 5, vsync: this, initialIndex: 0);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: TabBar(
controller: _tabController,
labelColor: Colors.yellow[800],
unselectedLabelColor: Colors.grey[800],
indicatorColor: Colors.transparent,
tabs: [
Tab(icon: Icon(Icons.local_grocery_store_outlined)),
Tab(
icon: Icon(Icons.card_giftcard_outlined),
),
Tab(
icon: Icon(Icons.fastfood_outlined),
),
Tab(
icon: Stack(
children: [
Icon(Icons.shopping_bag_outlined),
new Positioned(
top: 0.0,
right: 0.0,
child: CircleAvatar(
radius: 8.0,
backgroundColor: Colors.yellow[800],
child: Center(
child: Container(
padding: EdgeInsets.all(2),
child: Text(
/*Number of item in cart*/,
style: TextStyle(
color: Colors.black54,
fontSize: 10.0,
fontWeight: FontWeight.w500),
),
}),
),
),
)),
],
),
),
Tab(
icon: Icon(Icons.person_outline_outlined),
),
],
),
body: TabBarView(controller: _tabController, children: [
Store(),
Text("page"),
Text("page"),
CartPage(),
UserPage()
]),
);
}
}
I am using StreamBuilder to display the cart to the user.
My Firestore Structure
