Sunday, 6 September 2020

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

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 used return 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



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

No comments:

Post a Comment