Flutter - Map not working when addAll function call

1,512

You are using the map method to do something for each element of item['dates']. That doesn't work because the map operation is lazy and doesn't do anything until you start using the result. You can call .toList() on the result to make it do all the computations, but that's a roundabout way to do it.

Use forEach instead to eagerly do something for each element, or, even better, use a for-in loop:

item['dates'].forEach((date) { ... });

or

for (var date in item['dates']) {
  var key = DateTime.parse(date['date']);
  obj.addAll({key: ['list']});
  // or just:
  // obj[key] = ['list'];
}
Share:
1,512
ssuhat
Author by

ssuhat

Love to learn a new thing in programming world.

Updated on December 13, 2022

Comments

  • ssuhat
    ssuhat over 1 year

    This the code I have right now (I'm using Mobx):

    @observable
    ObservableMap dates = ObservableMap();
    
    @action
    void getDate() {
      final Map obj = {};
      final map = item['dates'].map((date) {
        DateTime key = DateTime.parse(date['date']);
    
        obj.addAll({
          key: ['list']
        });
      });
    
    //    print(map);
      dates.addAll(obj);
    }
    

    I have function to call query and call getDate function.

    At my UI I just call the dates but it won't return any value. The value only return if the print syntax not comment.

    Any solutionn?

  • ssuhat
    ssuhat over 4 years
    thank you. just learn something new. Map is lazy. I thought for statement will reduce performance.