简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM