我的主要问题是下面的代码对我来说运行良好,但它不是优化过的。我有一个包含以下MySQL请求的PHP文件:
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;}
在我的 Dart 应用程序中,我有以下类
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, ); } }
现在我有如下Future
函数来从数据库中获取返回的单行数据:
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.');
}
}
这对我来说很好用,但正如你所看到的,Future
函数正在创建客户列表,而这个列表当然只有一个项目,所以我使用了return listOfClients.first;
。现在我的问题是如何优化我的Future函数,使其仅返回一个客户,如下所示:
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
}
提示:这篇文章的标题有点令人困惑,请编辑提出改建议。
nom
,prenom
,age
FROMclient
WHEREcode
LIKE '$code limit 1'"; - farouk osama