Home > Mobile >  Flutter, Dart, add nested map to map
Flutter, Dart, add nested map to map

Time:12-12

var a = {
   'field1' : 'one'
   'field2' : 'two'
}

and then I want to add map b.

so I tried

a['b'] = {
  'nestedKey':{
     'field1' : 'one'
   }
};

but it occurs error. how do I acheive this?

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String?' of 'value'

eamirho3ein's answer is working but this is still not working I add more this is not working

                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(
                              builder: (context) => ScreenB(
                                    args: {
                                      'oldfield': 'old' 
                                    },
                                  )),
                          (Route<dynamic> route) => false);




import 'package:flutter/material.dart';

class ScreenB extends StatelessWidget {
  final args;
  const ScreenB({Key? key, required this.args}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    args['newfield'] ={
      'nested':{
        'field1' : 'one'
      }
    };
    print($args);
    return Container();
  }
}

CodePudding user response:

You need to define a as Map<String, dynamic> like this:

Map<String, dynamic> a = {'field1': 'one', 'field2': 'two'};
a['b'] = {
   'nestedKey': {'field1': 'one'}
};

print("result = $a"); // result = {field1: one, field2: two, b: {nestedKey: {field1: one}}}

when you define a as var, by default it takes Map<String, String> for its type and when you try to pass b, because b's value is an other map so you can't set it, a only accept string for its value. So you need to change a type to Map<String, dynamic>.

  • Related