Home > database >  Flutter: How to store specifc data from api response in a list
Flutter: How to store specifc data from api response in a list

Time:09-09

I have an api which returns json object as response. I have to store all the 'prefix_number' from response into list to later use it in a dropdown. I am trying to do it but no success.

here is response from api

[{prefix_number: 50}, {prefix_number: 51}, {prefix_number: 52}, {prefix_number: 53}, {prefix_number: 54}, {prefix_number: 55}, {prefix_number: 56}, {prefix_number: 57}, {prefix_number: 58}]

Here is my a list where i want to store it

List<String> prefixList = [];

here is my method

 Future getNumberPrefixes() async {
    var url = Uri.parse(AppApis.getPrefixesApi);
    final response = await http.get(url);
    print(response.statusCode);
    if (response.statusCode == 200) {
      Map data = jsonDecode(response.body);
      print(data);
      // print(data['data'][0]['prefix_number']);
      notifyListeners();
    } else {
      print("Failed");
    }
  }

Please help

CodePudding user response:

Give this a go:

  final data = jsonDecode(payload) as List<dynamic>;
  final prefixList = data.map((d) => (d as Map<String, dynamic>)["prefix_number"].toString()).toList();
  print(prefixList);

Here is a working example: https://dartpad.dev/?id=26e63a1baa818af7f3bea41a57eb1556

CodePudding user response:

Here is my code for you.

Future getNumberPrefixes() async {
    var url = Uri.parse(AppApis.getPrefixesApi);
    final response = await http.get(url);
    print(response.statusCode);
    if (response.statusCode == 200) {
      Map data = jsonDecode(response.body);
     
     //ADD Following lines to your code.

      for(int i=0; i< data.length; i  ){
        prefixList.add(data[I]["prefix_number"].toString());
      }


      print(data);
      notifyListeners();
    } else {
      print("Failed");
    }
  }
  • Related