jsondartdart-http

How I can manually iterate and filter some items from a json that may or many not contain an array?


In my application I make an api Class:


import 'package:http/http.dart' as http;
import 'dart:convert';

class Api 
{
  final String __baseUrl = "https://api.example.com"
  String? __token="";
  Future<List Stores> login(String username, String password) async {
     Uri url = Uri.parse(__base_url + "/login");
     var response = await http.post(url, body: {
         'email': email,
         'password': password
       }, headers: {
         "Accept": "application/vnd.api.myapi.v3+json",
        "Accept-Language": "en"
      });
      
      // I ommin status code checks for simplicity in question
      var responseJson = json.decode(response.body);
      __token = responseJson['tekken'];
      
      var stores = responseJson['stores']
      // Somehow filter and iterate the stores.
  }
}

And In order to keep myself controlled and sane I also made my own class stat maps the nessesary data that I want:

class Store
{
   final String id;
   final String name;

   const Store(this.id,this.name);
}

The final response of json is:

{
  "tekken":"cdasddfadadqa",
  "stores":[
    {
      "id":"cfsdsafsddsfdsf",
      "profile": [{"title":"Colomnian Store","lang":"en"},{"title":"Κολομβιανο χασίς","lang":"el"},]
      "sels_drugs":true
    },
    {
      "id":"cfsdsafsddsfdsf",
      "profile": [{"title":"Kuma Bear","lang":"en"},{"title":"Αρκουδάκι","lang":"el"},]
      "sels_drugs":false
    }
  ]
}

What I want to achieve is to create a List full of stores that are being mapped using the class Store. As you can see I want to get a subset of the provided data so anwers like these ones is not what I want.

How I can manually iterate the "stores" items filter them by sels_drugs key to be false and return a list?

Can I just do stores.where((u) => u.sells_drugs).toList().map()? Also in case of stores is null or has no items I want to return an empty list instead of blow up my application. How I can do this?


Solution

  • An approach you can do it the following:

    Iterate the var stores using a loop and using a classic if place them into the nessesary list:

    var stores = responseJson['stores'];
    List<Store> storesToReturn = [];
    
    for(store in stores) {
       if(store.sellsDrugs){
          storesToReturn.add(Store(store.id, store['profile'][0]['title']));
       }
    }
    
    

    So the final class will be:

    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class Api 
    {
      final String __baseUrl = "https://api.example.com"
      String? __token="";
      
      // Some constructors here
    
      Future<List<Store>> login(String username, String password) async {
         Uri url = Uri.parse(__base_url + "/login");
         var response = await http.post(url, body: {
             'email': email,
             'password': password
           }, headers: {
             "Accept": "application/vnd.api.myapi.v3+json",
            "Accept-Language": "en"
          });
          
          // I ommin status code checks for simplicity in question
          var responseJson = json.decode(response.body);
          __token = responseJson['tekken'];
          
          var stores = responseJson['stores']
    
          List<Store> storesToReturn = [];
    
        for(store in stores) {
         if(store.sellsDrugs){
          storesToReturn.add(Store(store.id, store['profile'][0]['title']));
         }
        }
    
        return storesToReturn;
      }
    }