1
votes

With a basic Flutter app, I'm working on getting data out of my Realtime Firebase database and rendering it in a FirebaseAnimatedList. My data looks something like:

Firebase image

I want to take each item name and render it in the FirebaseAnimatedList, and then have a delete icon function to remove it from the list when engaged, and also update the total sodium and calorie counts for the specific day. My code to access the data snapshot looks like:

  formattedDate = formatter.format(now);
    callLetters = formattedDate;
    final FirebaseDatabase database = FirebaseDatabase(app: widget.app);
    _callLettersRef = database.reference().child('User').child('DietVals').child(formattedDate).child('Meals');

I query the database as so, and it returns the following list in my app. What I'm not quite sure about is the best way to access the children of calories and sodium directly from the same snapshot of "meals".

 Flexible(
    child: new FirebaseAnimatedList(
        shrinkWrap: true,
        query: _callLettersRef, itemBuilder: (BuildContext context, DataSnapshot snapshot,
        Animation<double> animation,
        int index){
      return new ListTile(
        trailing: IconButton(icon: Icon(Icons.delete), onPressed: () =>{
            ref.child('User').child('DietVals').child(formattedDate).child('Calories').set(ServerValue.increment(-!NOTSUREHOWTOACCESSTHECALORIEVALUE)),
          ref.child('User').child('DietVals').child(formattedDate).child('Sodium').set(ServerValue.increment(-!NOTSUREHOWTOACCESSTHESODIUMVALUE)),
            _callLettersRef.child(snapshot.key).remove(),}),
        title: new Text(snapshot.key + "\n(Calories: " + snapshot.value.toString() + ")"
        ),
      );
    })
),

enter image description here

Basically, I'm just displaying the title of the meal (via snapshot.key) and the calories and sodium (the two children) via snapshot.value. But I would much prefer to display the calories and sodium separately, and be able to access both of their values to reset the counts of total calories and sodium if someone hits the delete key. Would anyone have a thought how to best manage this?

1

1 Answers

1
votes

When you call value on a DataSnapshot object that is not a single value, you get back from Map<String, dynamic> of the values under that path. So you can get the value of a specific property from that map.

So instead of new Text(snapshot.key + "\n(Calories: " + snapshot.value.toString() + ")") do something like this:

new Text(
  snapshot.key + "\n" + 
  "(Calories: " + snapshot.value["calories"].toString() + ")"
)

If you have any further nested objects under the top-level Map, their values would show up as another Map<String, dynamic> in the result.