Home > Blockchain >  I can't use .insert to add object into array with Dart
I can't use .insert to add object into array with Dart

Time:12-09

I'm trying to insert an object into array of objects. The idea is just add the content of the object if the object already exist but I don't understand why I can't use the .insert

I have tried using the .insert and adding the object into the array.

void main() {

  var arr = [
    {
      "shelf1": [
        {
          "Entry": "something",
          "Status": "",
          "Account": "",
          "Shelf": "A",
          "Address": "",
          "Result": null
        }
      ]
    },
    {
      "shelf2": [
        {
          "Entry": "something",
          "Status": "",
          "Account": "",
          "Shelf": "A",
          "Address": "",
          "Result": null
        }
      ]
    },
    {
      "shelf3": [
        {
          "Entry": "something",
          "Status": "",
          "Account": "",
          "Shelf": "A",
          "Address": "",
          "Result": null
        }
      ]
    }
  ];

  var object = {
    "shelf1": {
      "Entry": "something2",
      "Status": "",
      "Account": "",
      "Shelf": "shelf",
      "Address": "",
      "Result": null
    }
  };

  arr.insert(0, object);

  print(arr);
}

CodePudding user response:

The arr has a type of List<Map<String, Map<String, List<Map<String, String>>>>> and the object you declared has a type of Map<String, Map<String, String>>. This is because using var, the type is automatically inferred based on the assigned value. Since you're trying to add an object of an incorrect type an error is thrown.

So your new object should be made like the following to be inserted normally:

var object = {
  "shelf1": [{         // note that I made this inside a List []
    "Entry": "something2",
    "Status": "",
    "Account": "",
    "Shelf": "shelf",
    "Address": "",
    "Result": null
  }]
};
  • Related