skip to Main Content

I’m trying to create a nested map in dart :

static Map<String, Map<String, dynamic>> items = new Map<String, Map<String, dynamic>>();

and add values to this map when pressing a button :

Mainclass.items.addAll({
    "keyname" : {
        "firestvalue": 100, // cghange every press
        "secondvalue": 100 // cghange every press
    }
}); 

This is not working, it everytime shows length 1 :

print("length" + account.items.length.toString()); 

Any suggestions ?

2

Answers


  1. here is an implementation how you can do
    you can make function addValuesToMap()

    Map<String, Map<String, dynamic>> items = {};
    
      void addValuesToMap() {
        String keyName = 'keyname';
        int firstValue = 100;
        int secondValue = 100;
    
        setState(() {
          items[keyName] = {
            'firstvalue': firstValue,
            'secondvalue': secondValue,
          };
        });
      }
    

    then this function you can call in elevated button

    ElevatedButton(
          onPressed: () {
            addValuesToMap();
          },
          child: Text('Add Values'),
        )
    
    Login or Signup to reply.
  2. I am not sure what you expect to happen. However, if you want to dump values into a map of map, you want to maintain a key/index for each inner map you add.

    Map<String, Map<String, dynamic>> items = {};
    
      void addValuesToMap() {
        String keyName = 'keyname';
        int firstValue = 100;
        int secondValue = 100;
    
        setState(() {
          items["${items.length}"] = {
            keyname: {
                "firestvalue": firstValue, // change every press
                "secondvalue": secondValue // change every press
             }
           };
        });
      }
    

    You can call the addValuesToMap() function from the onpressed of a button.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search