How create a class object from JSON inside a Future function in dart? How create a class object from JSON inside a Future function in dart? dart dart

How create a class object from JSON inside a Future function in dart?


If the Get_only_one_situation method is written correctly, it should return only one value, You only have to decode it, like this:

const uri = 'http://10.0.2.2/re/App_agent/agent.php';      Future<Situation> fetchOneSituation(String ID) async {            var map = Map<String, dynamic>();            map['action'] = 'Get_only_one_situation';            map['ID'] = ID;       var response = await http.post(uri, body: map);        if (response.statusCode == 200) {          return Situation.fromJson(json.decode(response.body));          // You probably need this          // return Situation.fromJson(json.decode(response.body)['data'])        } else {          throw Exception('Failed to load data.');        }      }

After you updated your question, it became clear to me that you are fetching all sectors using this action Get_only_one_situation, and this is not preferred.

If the entire table must be fetched, all you need to do is fetch the appropriate item using the firstWhere method, like this:

Future<Situation> fetchSituation(String ID) async {  var map = Map<String, dynamic>();  map['action'] = 'Get_only_one_situation';   var response = await http.post(uri, body: map);  if (response.statusCode == 200) {    final items = json.decode(response.body).cast<Map<String, dynamic>>();    List<Situation> listOfSituations = items.map<Client>((json) {      return Situation.fromJson(json);    }).toList();    return listOfSituations.firstWhere((item)=>item.ID==item.ID);  } else {    throw Exception('Failed to load data.');  }}

Of course, I do not recommend this method, because querying on the database is faster than the code in a flutter, Especially with so much data.