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'
CodePudding user response:
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']);
}