0

How can i show the total amount in the bottom navigation bar... The app uses firebase backend... I have a filed in my database name total price of each item... Now I want to fetch the total price of each item and then add it and display in the bottom navigation bar..

I have attach my firebase backend screen shot.. what i need is to get all the value of the field 'total' add it up and show it in the bottom bar below the Total which is hardcoded as 999 currently section... It would be helpful if some let me know how to do it.. I am new to app development and flutter as well

enter image description here

enter image description here

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:fluttertoast/fluttertoast.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
 
class _MyAppState extends State<MyApp> {
 
 
  final myController = TextEditingController();  ///Alert Dialog box input text myController will be use to store the number of qty
  String id;
  var qty;
  var price;
  var total;
 
 
 
 
 
  @override
  Widget build(BuildContext context) {
   
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home:Scaffold(
        bottomNavigationBar: new Container( //// Bottom Naviagtion Bar for check out and Total price
      color: Colors.white,
          child:  Row(
            children: <Widget>[
              Expanded(child: ListTile(
                title: Text("Total"),
                subtitle: Text("Rs 999"),
              ),),
              Expanded(
                child: MaterialButton(onPressed:() {},
                child: Text("Check Out",style: TextStyle(color: Colors.white),),
                color: Colors.red,) ,
              )
            ],
          ),
        ),
        appBar: AppBar(title: Text('MyKart'),
            ),
        body: (
            StreamBuilder(
              stream: Firestore.instance.collection('KartDetails').snapshots(),
 
 
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasData) {
 
                  return ListView.builder(
                    itemCount: snapshot.data.documents.length,
 
                    itemBuilder: (context, index) {
 
                      DocumentSnapshot kartDetails = snapshot.data.documents[index];
                      return Container(
                        height: 150,
                        child: Card(
                          elevation: 10,
                          child: Container(
                            height: 100,
                            width: 100,
                            child: Row(
                              children: <Widget>[
                                Container(
                                  width: 100,
                                  height: 100,
                                  child: Image.network(kartDetails['img']),
                                ),
                                Container(
                                  child: (Text(kartDetails['item'])),
                                ),
                                Container(
 
                                  width: 50,
                                  child: (Text('Rs '+kartDetails['price'].toString(),textAlign: TextAlign.end,)),
                                ),
                                Container(
                                  margin: EdgeInsets.only(left: 20),
                                  height: 120,
                                  width: 50,
                                    color: Colors.white10,
                                  child: Column(
                                    children: <Widget>[
                                      RaisedButton(
                                        color: Colors.grey,
                                        onPressed: (){
                                          showDialog(context: context,
                                          builder: (BuildContext context){
                                            return Dialog(
                                              child: Container(
                                                height: 250,
                                                color: Colors.white10,
                                                child: Container(
                                                  margin: EdgeInsets.all(40.0),
                                                  child: Column(
                                                    children: <Widget>[
                                                      TextField(
 
                                                        controller: myController,
                                                        keyboardType: TextInputType.number,
                                                        decoration: InputDecoration(hintText: 'Enter the Quantity'),
 
                                                      ),
                                                      Container(
                                                        height: 50,
                                                      ),
                                                      RaisedButton(
 
                                                        color: Colors.blue,
                                                        child: Text('Submit'),
 
 
                                                        onPressed: () async{
 
 
 
                                                          
 
                                                          qty = myController.text;
//==================================================================Total Number of QTY ENTERED==========================================//
 
                                                          if (int.parse(qty)>0 && int.parse(qty)>=5) {
                                                            CollectionReference collectionRefernce = Firestore
                                                                .instance.collection(
                                                                'KartDetails');
                                                            QuerySnapshot querySnapshot = await collectionRefernce
                                                                .getDocuments();
                                                            querySnapshot
                                                                .documents[index]
                                                                .reference
                                                                .updateData(
                                                                {"quantity": qty});
 
//==================================================================Calculate price for each product==========================================//
                                                            price = kartDetails['price'];
                                                            total=int.parse(qty)*price;
                                                            querySnapshot
                                                                .documents[index]
                                                                .reference
                                                                .updateData(
                                                                {"total": total});
 
                                                            print(myController
                                                                .toString());
                                                            Navigator.of(context)
                                                                .pop();
                                                            myController.clear();
                                                            Fluttertoast.showToast(msg: "Quantity Updated",
                                                                toastLength: Toast.LENGTH_LONG,
                                                                gravity: ToastGravity.CENTER,
                                                                timeInSecForIosWeb: 1,
                                                                backgroundColor: Colors.red,
                                                                textColor: Colors.white,
                                                                fontSize: 20.0
                                                            );
                                                          }
                                                          else if(int.parse(qty) < 5 || int.parse(qty)<0) {
                                                            Fluttertoast.showToast(msg: "Minimum 5 quanity",
                                                                toastLength: Toast.LENGTH_LONG,
                                                                gravity: ToastGravity.CENTER,
                                                                timeInSecForIosWeb: 1,
                                                                backgroundColor: Colors.red,
                                                                textColor: Colors.white,
                                                                fontSize: 20.0
                                                            );
                                                            myController.clear();
                                                          }
                                                          else  {
 
                                                            Fluttertoast.showToast(msg: "Please enter valid quantity",
                                                                toastLength: Toast.LENGTH_LONG,
                                                                gravity: ToastGravity.CENTER,
                                                                timeInSecForIosWeb: 1,
                                                                backgroundColor: Colors.red,
                                                                textColor: Colors.white,
                                                                fontSize: 20.0
                                                            );
                                                            myController.clear();
                                                          }
 
                                                          //Firebase query
                                                        },
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            );
 
                                          });
                                        },
 
 
                                        child: Icon(Icons.shopping_basket),
 
                                      ),
                                      Container(
                                        height: 20,
                                      ),
                                      RaisedButton(
                                        color: Colors.grey,
                                        child: Icon(Icons.delete,color: Colors.black87,),
                                      )
                                    ],
                                  ),
                                ),
                                Column(
                                  children: <Widget>[
                                    Container(
                                      margin: EdgeInsets.only(left: 3),
                                      height: 50,
                                      width: 70,
                                      child: Center(child: Text('Quantity')),
                                    ),
                                    Container(
 
                                      width: 70,
                                      child: Center(child: Text((kartDetails['quantity']).toString())),
                                    ),
                                    Container(
                                      margin: EdgeInsets.only(top: 25),
 
                                      child: Center(child: Text('Total Price')),),
                                    Container(
                                      margin: EdgeInsets.only(left: 3),
 
                                      width: 70,
                                      child: Center(child: Text(("Rs " + (kartDetails['total']).toString()))),
                                    ),
 
                                  ],
                                ),
 
 
 
 
                              ],
                            ),
 
                          ),
                        ),
                      );
                    },
 
 
                  );
                }
                else{
                  return  Center(
                    child: Container(),
                  );;
                }
              },
 
 
 
            )
        ),
      ),
    );
  }
}
  • Please edit this question and provide more informations. What is this image exactly? Is it what you actually have or what you'd like to have? What does your bottomNavigationBar code looks like? What have you already tried? – Didier Peran Ganthier Jul 27 '20 at 13:14
  • I edited the question could you please check –  Jul 27 '20 at 15:54
  • I posted my answer below. Let me know if you need anything else – Didier Peran Ganthier Jul 27 '20 at 16:16
  • Its working perfectly but there is only one problem the Text field I mean the UI part remains constant it changes only after the App is restarted again... :( ... Is there ant way i can do it without restarting the app I mean as soon as the qty is updated –  Jul 28 '20 at 00:24
  • You can either use a RefreshIndicator (Wrap your Scaffold in it) or this answer could help you . https://stackoverflow.com/questions/60942014/how-to-see-changes-in-flutter-app-when-changing-values-in-firebase-realtime-data it seems related to what you want to do. – Didier Peran Ganthier Jul 28 '20 at 01:06
  • Hi I cannot use refresh indicator as it would promt the user to pull the screen down to refresh the cart... Also I have been through the stack overflow question... How can I use the onvalue... It would be helpful if you can show me... Thank you in advance –  Jul 28 '20 at 09:57
  • Thanks Sir with lil modification its working now... Thanks for your help –  Jul 29 '20 at 04:41
  • Great. I'm glad you solved your issue. – Didier Peran Ganthier Jul 29 '20 at 10:47

2 Answers2

0

This is a very vague question, so I will give a shot at one method of solving this. In order to do this you will need some sort of state management solution. I suggest using provider. Flutter has a tutorial on provider here. Essentially you will have to create a ChangeNotifier that every time would onAddItem and onDeleteItem and call notifyListeners() whenever you add or delete items. Then your bottom bar would simply use a Consumer to get the values from your ChangeNotifier. As I said this is just one approach, but since you did not give a replicable example this is the best I can do.

Gabe
  • 5,643
  • 3
  • 26
  • 54
  • Hi I am very new to flutter . I have edited the question. Could you please help me –  Jul 27 '20 at 15:56
  • @RetartedCoder look at DidierPeran's answer for this. I would like to point out, that it's not a great idea to store your cart in Firebase, that is something that would better be managed locally, but if you want to use the same cart across multiple devices than I suppose it would work. – Gabe Jul 27 '20 at 18:41
  • How can i do that locally can you just let me know the topic so that i can learn it –  Jul 27 '20 at 19:13
  • start researching provider, I would google Filled Stacks, he has a lot of good videos, this would be a good one to start: https://www.filledstacks.com/post/flutter-and-provider-architecture-using-stacked/ – Gabe Jul 27 '20 at 19:20
  • Say I use sqfite to store cart details but how can I get the image path??? It is store in firebase –  Jul 27 '20 at 20:32
  • I don't know anything about sqflite, sorry – Gabe Jul 27 '20 at 21:39
0

You can easily do it with this method:

  var totalCartValue = 0;

   String getCartTotal() async {

    QuerySnapshot snapshot = await Firestore.instance
        .collection('KartDetails')
       .getDocuments();

    snapshot.documents.forEach((doc) {
      setState((){
        totalCartValue += doc.data['total'];
      });
    });
    return totalCartValue.toString();
}

P.S: This method will give you the total of all values in the KartDetails collection not the total for the current user, for the current user it should be like this:

var totalCartValue = 0;

String getCartTotal() async {

    QuerySnapshot snapshot = await Firestore.instance
        .collection('KartDetails')
        .where("UID", isEqualTo: FirebaseAuth.instance.currentUser().toString())
       .getDocuments();

    snapshot.documents.forEach((doc) {
      setState((){
        totalCartValue += doc.data['total'];
      });
    });
    return totalCartValue.toString();
}

And use it in the UI that way:

class YourClassName extends StatefulWidget {

  @override
  _YourClassNameState createState() => _YourClassNameState();
}

class _YourClassNameState extends State<YourClassName> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: //your body code,
      bottomNavigationBar: BottomNavigationBar(
       items: [
        BottomNavigationBarItem(
          icon: new Icon(Icons.cart_shopping),
          title: new Text(totalCartValue),
        ),
      ]
     )
    );
  }
}

You should call it inside your initState so it gets executed whenever app starts:

@override
initState(){
  super.initState();
  getCartTotal();
}
  • Sir the thing is where to call the function... Also i called the function in the Cart Quantity increase icons on press function.. Just above the delete icon in the screen shot... the issue is the total quantity after addition remains the same i mean it doesnot change with quantity updation is added only once and then it remains the same I have checked using a print function. –  Jul 27 '20 at 18:56
  • I have pasted the code kindly let me know how to use it so that each i increase the quantity the total value is currently getting stored in firebase but how to get the total of the total value that is being stored in firebase and display in the UI –  Jul 27 '20 at 19:08
  • I edited my answer to get you to understand a lil bit more. Let me know if it helps. – Didier Peran Ganthier Jul 27 '20 at 20:25
  • If you want it to get updated every time something changes you can also call it in build – Didier Peran Ganthier Jul 27 '20 at 23:32