Home > other >  How to add an object in an array which is inside a nested object in Dart
How to add an object in an array which is inside a nested object in Dart

Time:10-03

The method 'push' isn't defined for the type 'Object'. I'm getting this error if I try to add a another procedure in the values array.

void main() {
  var myset = {
           "procedureResult": {
            "procedureSections": [
                                  {
                                    "section": "BasicInformation",
                                     "values": [
                                          {
                                             "procedure": "Angio"
                                          }
                                         ]
                                   }
                                  ]
                                }
                              };

   myset['procedureResult']!['procedureSections']![0]['values']!.push({'procedure2':'MRI'})
   print(myset['procedureResult']!['procedureSections']![0]['values']!.push({'procedure2':'MRI'}));
     }

CodePudding user response:

Add type for the list using angel brackets and use .add method instead of .push.

var myset = {
  "procedureResult": {
    "procedureSections": <Map>[ // like this
      {
        "section": "BasicInformation",
        "values": [
          {"procedure": "Angio"}
        ]
      }
    ]
  }
};

myset['procedureResult']!['procedureSections']![0]['values']!.add({'procedure2': 'MRI'});
print(myset['procedureResult']!['procedureSections']![0]['values']);

Or use as to cast procedureSections's value to a List and use .add method instead of .push..

var myset = {
  "procedureResult": {
    "procedureSections": [
      {
        "section": "BasicInformation",
        "values": [
          {"procedure": "Angio"}
        ]
      }
    ]
  }
};

(myset['procedureResult']!['procedureSections']![0]['values']! as List).add({'procedure2': 'MRI'});
print(myset['procedureResult']!['procedureSections']![0]['values']);
  • Related