skip to Main Content

I am new to Flutter. I am facing some issues while updating a list.

Currently, I have a list with some keys and values as follows:

[
  {filename: aa}, 
  {filename: bb.txt}, 
  {filename: cc.txt}
] 

And I want to update the above list by adding one more parameter called isPresent and update it as follows by doing some process on current data:

[
  {filename: aa,
   isPresent: false}, 
  {filename: bb.txt,
   isPresent: true}, 
  {filename: cc.txt,
  isPresent: false}
] 

How to do that any idea?

To achieve the above updated list I am using the following code

final List<Map<String, dynamic>> list = [...fetchJsonData['data']];
list.asMap().forEach((key, value) async {
  Directory? directory;
  directory = await getExternalStorageDirectory();
  File file = File("${directory!.path}/${list[key]['filename']}");
  await io.File(file.path).exists();
  bool isExists = io.File(file.path).existsSync();
  print(isExists);
  list[key]['isPresent'] = isExists;
});
fileList = list;
print(fileList);

but does not work with Await I think. Let me know if I am missing something.

3

Answers


  1. You can do this for example

    main() {
      List<Map<String, dynamic>> data = [
        {'filename': 'aa'},
        {'filename': 'bb.txt'},
        {'filename': 'cc.txt'}
      ];
    
      data[0]['isPresent'] = false;
      data[1]['isPresent'] = true;
      data[2]['isPresent'] = false;
    
      print(data);
      //[{filename: aa, isPresent: false}, {filename: bb.txt, isPresent: true}, {filename: cc.txt, isPresent: false}]
    }
    
    Login or Signup to reply.
  2. can you try below code and check :

    List<Map<String, dynamic>> originalList = [
      {"filename": "aa"},
      {"filename": "bb.txt"},
      {"filename": "cc.txt"}
    ];
    
    List<Map<String, dynamic>> updatedList = originalList.map((item) {
      String filename = item["filename"];
      bool isPresent = /* Perform your process here based on the filename */;
      
      return {
        "filename": filename,
        "isPresent": isPresent,
      };
    }).toList();
    
    Login or Signup to reply.
  3. Sure,

    void updateList() {
      
      List<Map<String, dynamic>> data = [
        {"filename": "aa"},
        {"filename": "bb.txt"},
        {"filename": "cc.txt"}
      ];
    
      for (var file in data) {
        file["isPresent"] = file["filename"].endsWith(".txt");
      }
      print(data);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search