ArthurEKing
ArthurEKing

Reputation: 158

Accessing Variable-Values from Complex Lists of Nested Map Objects in Flutter

I'm receiving a response from a server-call, which I've decoded from JSON into a List

Now any of the level 1 list-values I can access, no issues. However, some of the values I'm receiving are complex, instead of a simple data-type like a String or an int, it is a Map object, with nested variables inside.

How do I get access to those?

I can't create a class to parse the Map objects into, because they could be of many different kinds, and there's no way for me to understand what they will be in advance.

Examples of a server response I could receive:

[{
  info1: something,
  info2: something else,
  info3: something something else,
  info4: [{
    object1: data,
    object2: data2,
    object3: data3
  }],
  info5: something something something else,
}]

At the same time, I cannot know in advance whether or not I will be receiving a response at any given point that will contain such a map object, or which kind it will be. So how do I get access to those variables? Right now, if I type

print(list[0][info4]);

I would get

[{object1: data, object2: data2, object3: data3}]

From there, what I need to be able to do, is get the individual variable data, e.g. for object1 inside info4

data

So I have the data, but after getting the individual index, how to I access the data inside that object? What notation do I use? Everything I've tried either returns null, or type errors.

Also, the line of code I'm using to decode the server response is as follows.

List<dynamic> data2 = jsonDecode(response.body);

So the data is currently in the format of List and if I need to use some other line to decode it into a different format, or something, that might give you an idea where I'm starting from.

Upvotes: 1

Views: 1609

Answers (1)

ArthurEKing
ArthurEKing

Reputation: 158

Aha! Managed to figure it out. It's actually because of the brackets, and bracket-types.

Effectively, the [ bracket denotes a List, whereas the { bracket denotes a Map. I didn't understand this going in, so the notations I was using were confusing.

Now that I understand that, The notation works.

So in the above example, the method I would use to get access the to object1: data result, would be as follows.

 print(info[0][info4][0][object1]);

So in essence, due to the [] brackets, it's asking for an integer case to identify a given object, whereas the {} brackets are asking for a String case to identify to object instead. Once I understand this, the rest came automatically, and I was able to resolve the parsing of the data as needed.

Thank you for your insightful comments though!

Upvotes: 1

Related Questions