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

Viewed 413

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));
}
1 Answers

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.

Related