Search code examples
jsonflutterrestdartjsondecoder

Trouble extracting JSON data in Flutter


I'm trying to render a list of elements in Flutter and the list data is coming from a REST API. However, I'm having trouble understanding how to parse this data correctly. I want the parsed data to look like this:

['Chicken roll', 'Fresh salads', 'Wrape', 'Pizza', 'Fried Chicken', 'Veggie', 'Burgers']

This is the JSON object:

{
    "status":true,
    "error_message":"",
    "success_message":"Task completed successfully.",
    "data":[
        {
            "id":1064,
            "name":"Chicken roll"
        },
        {
            "id":1061,
            "name":"Fresh salads"
        },
        {
            "id":1059,
            "name":"Wrape"
        },
        {
            "id":1057,
            "name":"Pizza"
        },
        {
            "id":1055,
            "name":"Fried chicken"
        },
        {
            "id":1053,
            "name":"Veggie"
        },
        {
            "id":1051,
            "name":"Burgers"
        }
    ]
}

How do I achieve this? My current code is as follows:

var _categoryResponse;
  var _categoryData;
  var categoryData;
  List<String> allCategories;

  Future fetchCategories() async {
    _categoryResponse = await http.get(_categories);
    _categoryResponse = jsonDecode(_categoryResponse.body);
    _categoryData = _categoryResponse['data'].toString();
    categoryData = categoryDataFromJson(_categoryData);
  }

Solution

  • List<String> listOfNames = [];
    List<dynamic> data = json['data'] as List;
    
    data.forEach((item) => listOfNames.add(item['name']));
    
    print(listOfNames);
    

    Gives the following output:

    [Chicken roll, Fresh salads, Wrape, Pizza, Fried chicken, Veggie, Burgers]
    

    I'm assuming the variable json above contains your parsed JSON object (as given in the example).

    Not sure why you're converting JSON to String as its much easier to work with the dynamic map, at least when it comes to fetching particular attributes like the name of each object within the data list.

    Basically, the data key maps to a list of objects with attributes id and name. Hence, you can run a forEach() on the list obtained and fetch the name for each object in it.