Home > Net >  How to setState() in StreamBuilder()?
How to setState() in StreamBuilder()?

Time:10-27

  return ListView(
      children:
          snapshot.data!.docs.map((DocumentSnapshot document) {
    Map<String, dynamic> data =
        document.data()! as Map<String, dynamic>;
    // setState(() {
    //   allCalWorkout  = data['totalCal'];
    // });
    return Container(
      margin: EdgeInsets.all(20),
      child: ListTile(
          onTap: () {},
          title: Text(data['nameWorkout']),
          subtitle: Text(
              'set: ${data['set']} calories:${data['totalCal']}'),
          trailing: IconButton(
              onPressed: () async {
                // print(document.id);
                await delWorkout(document.id);
                setState(() {
                  _workout = getAllWorkout();
                });
              },
              icon: Icon(Icons.delete, color: Colors.red))),
    );
  }).toList());

My Screen

I want to sum all the calories in firebase name is "totalCal" and also how to store the total variable for passing to another page.

CodePudding user response:

 sum = data['totalCal'].fold(0, (sum, element) => sum   element['totalCal']!);
      print('sum2 = $sum2');

I don't its will work or not, but if you use fold method then you can sum the value

CodePudding user response:

According to the documentation, StreamBuilder will listen to changes in order to set its state, so the state is managed by new events that happen:

Widget rebuilding is scheduled by each interaction, using State.setState, but is otherwise decoupled from the timing of the stream.

The FlutterFire documentation includes an example on how to listen to Firestore for events that can be used to update the widget. The same documentation page has a guide on how to update a value in the Firestore document with the update method (in this case your totalCal amount resulting from adding all the calories). I followed the example and can confirm it works.

As for how to preserve your totalCal value between views, you can do this by storing this variable in a library file which is imported into all of your views, and then setting the value after doing a sum of all the calories will update it everywhere. You can review this related question for more details.

  • Related