0

I want to access the properties of this json object and display them for test purposes on the screen.

I can display the whole json object on the screen:

{
  "2021": {
            "januari": {
                "value": 100,
            },
            "februari": {
                "value": 200,
            },
        }
"2022": {
            "januari": {
                "value": 100,
            },
            "februari": {
                "value": 200,
            },
        }
}

This is how i display it:

 Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Page View'),
        ),
        body: Container(
            child: Card(
                child: FutureBuilder(
          future: getJson(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data);
            }
            return const Text("no data");
          },
        ))));
  }

It displays the json exactly like i showed with the example. I just wonder how i can access and show the properties for example "2021", "januari" and the value of "value" on the screen?

Edit

When i do: Text(snapshot.data['2021']['januari'])

i get: type 'String' is not a subtype of type 'int' of 'index'

4
  • Try Text(snapshot.data['2021']['januari']) Commented Dec 26, 2021 at 12:31
  • This is what i get when i do that: type 'String' is not a subtype of type 'int' of 'index' Commented Dec 26, 2021 at 12:33
  • try: Text(snapshot.data['2021']['januari']['value'].toString()) Commented Dec 26, 2021 at 14:42
  • still gives the same error Commented Dec 26, 2021 at 15:29

1 Answer 1

2

Here is sample for you. You can take it in dartpad. So to fix you behavior probably take your snapshot data and put it inside Map<dynamic,dynamic> and then use it like in code below.

import 'dart:convert';

String data = '''{
  "2021": {
    "januari": {
      "value": 100
    },
    "februari": {
      "value": 200
    }
  },
  "2022": {
    "januari": {
      "value": 100
    },
    "februari": {
      "value": 200
    }
  }
} ''';

void main() { 

  Map<dynamic,dynamic> json = jsonDecode(data);
  print(json.keys.first);
  print(json['2021'].keys.first);
  print(json['2021']['januari']['value']);
}
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.