how could I add the elements of a List <dynamic> to a List <Object> using flutter

139

I assume the fromMap method accepts a Map<String, dynamic>, so if you are sure that the content of tmp["messages"] actually is a map, you can do the following:

final messages = List<Map<String, dynamic>>.from(tmp["messages"] as List<dynamic>);
List<Message> finalList = messages.map((m) => Message.fromMap(m)).toList();
finalList.sort((a, b) => b.createdAt.compareTo(a.createdAt));

As long as your implementation of Message.fromMap is correct, this should get you a list of messages.

Share:
139
Admin
Author by

Admin

Updated on December 26, 2022

Comments

  • Admin
    Admin over 1 year

    dart code where i try to add element in messages to finalList (Don't work)

     List<Message> finalList = List();  //list where data should go
    if (tmp != null) {
      List<dynamic> messages = tmp["messages"];  //list where data come from
      for (var element in messages) {
        try {
          Message eltMsg = Message.fromMap(element);
          finalList.add(eltMsg);
        } catch (e) {
          print(e);
        }
      }
      finalList.sort((a, b) => b.createdAt.compareTo(a.createdAt));
    }
    
  • Admin
    Admin over 2 years
    i actually want that finalList receive all data from messages
  • TmKVU
    TmKVU over 2 years
    Well, if the rest of your code is correct, this should work with your loop