0

I want to store various data for my app in a single place, in a map. In JS, I'd store in a JSON file, and I want to use the same sort of approach, but struggling with Dart. I can't seem to work with nested lists or maps.

Here's essentially what I want to do:

var items = {
  "item1": {
    "message" : "aa",
    "nested1": {
       "message": "bb",
       "nested2" : {
          "message" : "cc"
      },
    }
  },
};

void main() {

  var message1 = items["item1"]?["message"];
  print(message1);
  print(message1.runtimeType);

  var message2 = items["item1"]?["nested1"]?["message"];
  print(message2);
  print(message2.runtimeType);  

  var message3 = items["item1"]?["nested1"]?["nested2"]?["message"];
  print(message3);
  print(message3.runtimeType);  

}

I've been struggling to make this work in Dartpad. message1 works as expected, but then I can't seem to work my way down the tree... Is this a shortcoming with map literals? Do I need to use constructors? Or am I missing something bigger?

1 Answer 1

2

Your problem is that items is inferred to be of type Map<String, Map<String, Object>>, but Object does not have an operator []. Therefore when you eventually extract that Object, you will not be able to do anything with it until you cast it a more specific type.

What you probably want instead is to explicitly declare items as Map<String, dynamic> to disable static type-checking on the Map's values:

var items = <String, dynamic>{
  "item1": ...
};

Of course, when you disable static type-checking, you are responsible for ensuring that the values you get from the Map are what you expect, or you will get NoSuchMethod or TypeError exceptions at runtime. If you do want static type-checking, you should use define custom classes instead of using a blob of key-value properties.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.