Adarsh Balu
Adarsh Balu

Reputation: 352

Nested Map operation in Dart

I have a Maps of type

Map<String,Map<String,bool>> outerMap;
Map<String,bool> innerMap_1 ,innerMap_2;

I need to nest innerMaps inside outerMap.

innerMap_1 = { 'time_1':true , 'time_2':false };
innerMap_1 = { 'time_3':false ,'time_4':true };

outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };

I need to store outerMap as a string on the Sqlite Database. When I try

jsonEncode(outerMap);

There is an error because it is nested.

How to effectively convert the outerMap to String and then convert that string back to Map ?

Upvotes: 0

Views: 182

Answers (1)

Mavv3006
Mavv3006

Reputation: 65

outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };

The thing is that you had a spelling error and therefore there was an error. But in my solution I fixed that.

Another thing to notice is that in order to use the jsonEncode function you have to import the dart:convert package.

import 'dart:convert';

void main() {
  Map<String, Map<String, bool>> outerMap;
  Map<String, bool> innerMap_1, innerMap_2;

  innerMap_1 = {'time_1': true, 'time_2': false};
  innerMap_2 = {'time_3': false, 'time_4': true};

  outerMap = {'date_1': innerMap_1, 'date_2': innerMap_2};
  
  String json = jsonEncode(outerMap);
  print(json);
  print(jsonDecode(json));
}

You can test your dart code on dartpad.dev.

Upvotes: 2

Related Questions