Home > Software engineering >  dart/flutter : How to convert List of String into Map in dart
dart/flutter : How to convert List of String into Map in dart

Time:08-24

I got list of String from (Shared Preferences) and the result was :

['{id:5}' , '{id:6}']

and I want to check the value for each (id)

CodePudding user response:

Given that you have List and you want a Map<String,String?>, here is a way of doing it:

final list = <String>['{id:5}', '{id:6}'];

final newList = list.map((e) {
  final match = RegExp(r'{id:(\d )').firstMatch(e);
  return MapEntry('id', match?.group(1));
}).toList();

or if you just want a list of the id:

final newList = list.map((e) {
  final match = RegExp(r'{id:(\d )').firstMatch(e);
  return match?.group(1);
}).toList();

CodePudding user response:

First of all, this is the wrong way to store values in list, if you have just list of id , you have to make it like : List<String> l= ["1","2","3","4"];

then you can convert list to map as follow :

List<String> l= ["1","2","3","4"];
  Map<String,dynamic> mapp = {};

l.forEach((element) { 
  mapp["id"] = element;
});
  • Related