Home > front end >  How to get the value of a key from json in flutter?
How to get the value of a key from json in flutter?

Time:11-08

In my API I need to get the value from the "value" key of the readm pair.

"extra_info": [
                    {
                        "name": "readme",
                        "value": "**In this session, we will work on different activities using Toggle Board:**\nIdentify animals using characteristics\nRecognize the animals by listening to a song"
                    },
                    {
                        "name": "skill",
                        "value": "Play school"
                    },
                    {
                        "name": "sub_skill",
                        "value": "Toggle board"
                    }
                ],

I tried using like this but some case the index number will change.

hotsLevelController.other_list[0].extraInfo[0].value;

CodePudding user response:

Probably you have a json response which is come from HTTP request. so this can help you:

final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
  final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
  List<dynamic> itemsList = jsonResponse['extra_info'] as List<dynamic>;
  // print values
  for (var item in itemsList) {
    print((item as Map<String, String>)['value']);
  }
}

CodePudding user response:

Basic JSON serialization in Flutter is very simple. Flutter has a built-in dart:convert library that includes a straightforward JSON encoder and decoder. You can learn from here: https://docs.flutter.dev/development/data-and-backend/json

or you can use this function:

// findKey will me 'readme' in your case
// pass the json data iin json
findValue(dynamic json, String findKey) {
  final data = json.decode(json) as Map<String, dynamic>;
  List<Map<String, String>> items = data['extra_info'] as List<Map<String, String>>;

  for (var item in items) {
    if (item['name'] == findKey) {
      return item['value'];
    }
  }
  return null; //not found
}
  • Related