想要在底部的导航栏中传递总价 [英] Want to pass the total price in the bottom navigation bar in flutter

查看:62
本文介绍了想要在底部的导航栏中传递总价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在底部导航栏中显示总金额...该应用程序使用Firebase后端...我在数据库名称中归档了每个项目的总价...现在我想获取总价每个项目,然后将其添加并显示在底部导航栏中.

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..

我附上了我的Firebase后端屏幕截图.我需要获取字段总计"的所有值并将其加起来,并在总计(其硬编码为"999当前"部分)的底部栏中显示..如果有人让我知道如何做会很有帮助..我也是应用开发和开发的新手

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

推荐答案

您可以使用此方法轻松完成此操作:

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:此方法将为您提供KartDetails集合中所有值的总和,而不是当前用户的总和,对于当前用户,它应该像这样:

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

您应该在initState内部调用它,以便它在应用启动时立即执行:

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

@override
initState(){
  super.initState();
  getCartTotal();
}

这篇关于想要在底部的导航栏中传递总价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆