skip to Main Content

I have list of names want to add them to map and add each record of this map to list Like this

List<String> items = [
  'Item1',
  'Item2',
  'Item3',
  'Item4',
  'Item5',
  'Item6',
  'Item7',
  'Item8',
];
List all=[];
Map <String, dynamic>test={};
me(){
    for(int i=0; i<items.length;i++){
      test["one"]=items[i];
      test["check"]=false;
      all.add(test);
      
    }
  test["check"]=false); });
  print(all);
  

The output was

[{one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}, {one: Item8, check: false}]

The item8 was always repeated but I want this output

[{one: Item1, check: false}, {one: Item2, check: false}, {one: Item3, check: false}, {one: Item4, check: false}, {one: Item5, check: false}, {one: Item6, check: false}, {one: Item7, check: false}, {one: Item8, check: false}]

2

Answers


  1. You can use:

    final results = items.map((e) => {"one": e, "check": false}).toList();
    
    void main() {
      List<String> items = [
        'Item1',
        'Item2',
        'Item3',
        'Item4',
        'Item5',
        'Item6',
        'Item7',
        'Item8',
      ];
      
      final results = items.map((e) => {"one": e, "check": false}).toList();
      print(results);
    }
    
    

    Prints:

    [{one: Item1, check: false}, {one: Item2, check: false}, {one: Item3, check: false}, {one: Item4, check: false}, {one: Item5, check: false}, {one: Item6, check: false}, {one: Item7, check: false}, {one: Item8, check: false}]
    

    Or: using your approach with a for loop:

    final results = [];
      
      for (var i = 0; i < items.length; i++) {
        results.add({"one": items[i], "check": false});
      }
    
    Login or Signup to reply.
  2. You can do this:

    final all = items
        .map(
          (item) => {
            'one': item,
            'check': false,
          },
        )
        .toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search