How to iterate through every document and sum properties in Firestore with Flutter

281

If you want total of amunt for user this works:

FirebaseFirestore.instance
          .collection('Users')
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .collection('Coins')
          .snapshots()
        .listen((snapshot) {
      double tempTotal = snapshot.documents.fold(0, (tot, doc) => tot + doc.data['amount']);
      print(tempTotal.toString());
    });
Share:
281
elios_cama
Author by

elios_cama

Updated on January 01, 2023

Comments

  • elios_cama
    elios_cama over 1 year

    I'm creating an app in which you put the amount of crypto you have and then with an API it retrieves the amount with live data. Thing is I have this ListView with all the cards for all the cryptos but I'd like a Container at the bottom of the screen with the total of all the amounts. I don't know how to create a function that goes through every "Coins" of a user and then retrieve the amount of the total. Thing is in Firestore I only have the quantity and then in my HomePage with the cards there's the function with the Api that calculates the amount in usd. Could you help me to create some function which does that?

    Here's my code of my HomePage view :

    class HomeView extends StatefulWidget {
    const HomeView({ Key? key }) : super(key: key);
    
    @override
     _HomeViewState createState() => _HomeViewState();
     }
    
     class _HomeViewState extends State<HomeView> {
    
     double bitcoin = 0.0;
     double ethereum = 0.0;
     double tether = 0.0;
     double ultra = 0.0;
     double ternoa = 0.0;
     double dai = 0.0;
     double litecoin = 0.0;
     double cardano = 0.0;
     double stellar = 0.0;
     double tezos = 0.0;
     double elrond = 0.0;
     double dogecoin = 0.0;
     double solana = 0.0;
    
    
     @override
      initState() {
       updateValues();
      }
    
     updateValues() async {
    bitcoin = await getPrice("bitcoin");
    ethereum = await getPrice("ethereum");
    tether = await getPrice("tether");
    ultra  = await getPrice("ultra");
    ternoa = await getPrice("coin-capsule");
    dai = await getPrice("dai");
    litecoin = await getPrice("litecoin");
    cardano = await getPrice("cardano");
    stellar = await getPrice("stellar");
    tezos = await getPrice("tezos");
    elrond = await getPrice("elrond-erd-2");
    dogecoin = await getPrice("dogecoin");
    solana = await getPrice("solana");
    setState(() {});
    }
    
    @override
    Widget build(BuildContext context) {
    getValue(String id, double amount) {
      if (id == "bitcoin") {
        return (bitcoin * amount).toStringAsFixed(2);
      } else if (id == "ethereum") {
        return (ethereum * (amount)).toStringAsFixed(2);
      } else if (id == "ultra"){
        return(ultra*amount).toStringAsFixed(2);
      }else if(id == "coin-capsule"){
        return(ternoa*amount).toStringAsFixed(2);
      }else if (id == "dai"){
        return(dai*amount).toStringAsFixed(2);
      }else if (id == "litecoin"){
        return(litecoin*amount).toStringAsFixed(2);
      }else if (id == "cardano"){
        return(cardano*amount).toStringAsFixed(2);
      }else if (id == "stellar"){
        return(stellar*amount).toStringAsFixed(2);
      }else if (id == "tezos"){
        return(tezos*amount).toStringAsFixed(2);
      }else if (id == "elrond-erd-2"){
        return(elrond*amount).toStringAsFixed(2);
      }else if (id == "dogecoin"){
        return(dogecoin*amount).toStringAsFixed(2);
      }else if (id == "solana"){
        return(solana*amount).toStringAsFixed(2);
      }
      else {
        return (tether * amount).toStringAsFixed(2);
      }
    }
    
    return Scaffold(
      body : Row(
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(color: Colors.white),
            child: StreamBuilder(
              stream: FirebaseFirestore.instance
              .collection('Users')
              .doc(FirebaseAuth.instance.currentUser!.uid)
              .collection('Coins')
              .snapshots(),
              builder: (
                BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot){
                  if(!snapshot.hasData){
                    return Center(child: CircularProgressIndicator(),);
                  }
                  return ListView(
                    children: snapshot.data!.docs.map((document) {
                      return Padding(
                        padding: const EdgeInsets.only(top: 8, left: 15, right :15),
                        child: Container(
                          width: MediaQuery.of(context).size.width/1.3,
                          height: MediaQuery.of(context).size.height/12,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15.0),
                            color: Colors.blue,
                          ),
                          child: Row(
    
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              SizedBox(width: 5,),
                              Text("Coin : ${document.id}", style: TextStyle(color: Colors.white, fontSize: 18),),
                              Text("\$${getValue(document.id, document['Amount'])}",style: TextStyle(fontSize: 18,color: Colors.white)),
                              
                              IconButton(
                                onPressed: ()async{
                                  await removeCoin(document.id);
                                }, 
                                icon: Icon(Icons.close, color: Colors.red)
                                )
                              
                            ],
                          ),
                        ),
                      );
                    }).toList(),
                  );
                }
              ,
            ),
          ),
          
        ],
      ),
      
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          Navigator.push(context, MaterialPageRoute(builder: (context) => AddView()));
        },
        child: Icon(Icons.add, color: Colors.white,),
        backgroundColor: Colors.blue,
        ),
    );
    }
    }
    

    And here's the function for the api:

    Future<double> getPrice(String id) async{
    try{
    var url = "https://api.coingecko.com/api/v3/coins/" + id;
    var response = await  http.get(Uri.parse(url));
    var json = jsonDecode(response.body);
    var value = json['market_data']['current_price']['usd'].toString();
    return double.parse(value);
    }catch(e){
    print(e.toString());
    return 0.0;
    }
    }
    

    Any idea would be super helpul! Thank you guys!