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.

Comments
-
Asmoun over 1 year
My main issue is the code bellow works fine for me but it is not optimized, i have a PHP file that contains the following MySQL request :
if("GET_CLIENT" == $action){ $code = $_POST['code']; $db_data = array(); $sql = "SELECT `nom` , `prenom`, `age` FROM `client` WHERE `code` LIKE '$code'" ; $result = $conn->query($sql); $row = $result->fetch_assoc()) echo json_encode($db_data); $conn->close(); return;}
in my dart application i have the following class
Client
:class Client { String code; String nom; String prenom; Client({this.code, this.prenom, this.nom }); factory Client.fromJson(Map<String, dynamic> json) { return Client( code: json['code'] as String, nom: json['nom'] as String, prenom: json['prenom'] as String, ); } }
now to fetch the returned single row from the database i have the following
Future
function :Future<Client> fetchClient(String code) async { var map = Map<String, dynamic>(); map['action'] = 'GET_CLIENT'; map['code'] = code; var response = await http.post(uri, body: map); if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); List<Client> listOfClients = items.map<Client>((json) { return Client.fromJson(json); }).toList(); print(listOfClients.first.code); return listOfClients.first; } else { throw Exception('Failed to load data.'); } }
this works fine for me but i as you can see the
Future
function is creating a List of clients and this List of course has only one item so i usedreturn listOfClients.first;
now my question is how to optimize my Future function to return only one client like following :if (response.statusCode == 200) { final items = json.decode(response.body).cast<Map<String, dynamic>>(); Client client = .. somthing ?? // instead of List Client return client; // instead of return listOfClients.first }
PS: the tittle of this post is a bit confusing any suggestion to change it please edit
-
Asmoun over 3 yearsSalam , thanks for the help bro i updated my post i'm sure it was a bit misleading or confusing , the update will help to give me the solution . please update you answer since you have more info about my issue now .
-
Asmoun over 3 yearsthe following looks exactly what i want but it doesn't work
return Client.fromJson(json.decode(response.body));
-
farouk osama over 3 yearsI do not have PHP experience, but you only have to return one object instead of a list of objects for it to work.
-
farouk osama over 3 yearsIt appears that you are returning the value in the following form: [{"id":1,"name":"example"}] , And correct is {"id":1,"name":"example"}, without []
-
Asmoun over 3 yearsyeh i think that's the issue