Want to pass the total price in the bottom navigation bar in flutter

試著忘記壹切 提交于 2021-02-11 15:21:17

问题


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

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(),
                  );;
                }
              },
 
 
 
            )
        ),
      ),
    );
  }
}

回答1:


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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/63115524/want-to-pass-the-total-price-in-the-bottom-navigation-bar-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!