Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting LinkedHashMap<dynamic,dynamic> to HashMap<String,List<String>> in dart or flutter

Tags:

flutter

dart

Hi I am new to flutter and dart. I am facing difficulty in typecasting maps. I have saved some data on Firestore in the format of HashMap<String,List<String>>. In my flutter app when I am fetching this data, I am getting it in the format of LinkedHashMap<dynamic,dynamic>. I want to convert this LinkedHashMap into a HashMap<String,List<String>>. Please help.

LinkedHashMap<dynamic,dynamic> mapUserWatchlistCompanies= documentSnapshot.data['Watchlist']; // Fetched data.

HashMap<String,List<String>> hashMapUserWatchlist = ???//How can it be converted? Need help here.
like image 961
Abhijeet Kharatmol Avatar asked May 03 '19 13:05

Abhijeet Kharatmol


People also ask

What is LinkedHashMap in Dart?

An insertion-ordered Map with expected constant-time lookup. A non-constant map literal, like {"a": 42, "b": 7} , is a LinkedHashMap . The keys, values and entries are iterated in key insertion order. The map uses a hash-table to look up entries, so keys must have suitable implementations of Object.

How do you use the map in flutter?

To use Google Maps in your Flutter app, you need to configure an API project with the Google Maps Platform, following the Maps SDK for Android's Using API key, Maps SDK for iOS' Using API key, and Maps JavaScript API's Using API key.

How do you add data to dart map?

Using addEntries() method This method is used to add a collection of key/value pairs to a given map. Like the addAll() method, if a key already exists in the map, its value will be overwritten.


1 Answers

The typecast in dart it's a bit different than you would get in Java or Swift. In dart you have to correctly cast everything when dynamic is involved.

Now in your case you get a LinkedHashMap<dynamic, dynamic>, now in JSON case it's safe to assume that the keys will always be a String value, but the value for a key can be several types (number, string, boolean, map or list).

So if you have a JSON in the following form:

{
  "keyOne": ["One", "Two","whatever"],
  "keyTwp": ["roses", "are", "red"],
  "keyThree":["You", "know", "nothing", "john", "nonw"]
}

Which is a HashMap<String, List<String>>, but dart initially will get a LinkedHashMap<dynamic, dynamic>, you can safely convert it with the following code:

 LinkedHashMap<dynamic, dynamic> theParsedOne = .....
    HashMap<String, List<String>> newMap = HashMap.from(theParsedOne.map((key, value) {
      List<dynamic> values = List.from(value);
      return MapEntry(
          key.toString(),
          values.map((theValue) {
            return theValue.toString();
          }).toList());
    }));
like image 50
danypata Avatar answered Nov 15 '22 11:11

danypata