
本文档将指导你如何在 Flutter 应用中从 PHP API 获取数据,并使用 `Table` 组件将其动态地展示出来。我们将重点解决常见的空值问题,并提供完整的代码示例,帮助你构建一个数据驱动的表格。
首先,我们需要定义一个数据模型来映射从 API 返回的 JSON 数据。以下是一个示例 Model 类,它包含了一些常见的字段:
class Model {
Model({
this.id,
this.goodsRef,
this.loyer,
this.bnCode,
this.loyeeNo,
this.contactName,
this.contactTel,
this.bnDesc,
this.reqStatus,
this.eMail,
this.comments,
this.tender,
this.reqDate,
this.sscOffice,
this.sn, // 添加 sn 字段
this.name, // 添加 name 字段
this.address, // 添加 address 字段
this.phone, // 添加 phone 字段
});
final String id;
final int goodsRef;
final String loyer;
final String bnCode;
final int loyeeNo;
final dynamic contactName;
final dynamic contactTel;
final String bnDesc;
final String reqStatus;
final dynamic eMail;
final String comments;
final List<Tender> tender;
final DateTime reqDate;
final dynamic sscOffice;
final String sn; // sn
final String name; // name
final String String address; // address
final String phone; // phone
factory Model.fromJson(Map<String, dynamic> json) => Model(
id: json["\u0024id"] == null ? null : json["\u0024id"],
goodsRef: json["goods_ref"] == null ? null : json["goods_ref"],
loyer: json["loyer"] == null ? null : json["loyer"],
bnCode: json["bn_code"] == null ? null : json["bn_code"],
loyeeNo: json["loyee_no"] == null ? null : json["loyee_no"],
contactName: json["contact_name"],
contactTel: json["contact_tel"],
bnDesc: json["bn_desc"] == null ? null : json["bn_desc"],
reqStatus: json["req_status"] == null ? null : json["req_status"],
eMail: json["e_mail"],
comments: json["comments"] == null ? null : json["comments"],
tender: json["tender"] == null ? null : List<Tender>.from(json["tender"].map((x) => Tender.fromJson(x))),
reqDate: json["req_date"] == null ? null : DateTime.parse(json["req_date"]),
sscOffice: json["ssc_office"],
sn: json["sn"] == null ? "" : json["sn"], // 处理 sn 空值
name: json["name"] == null ? "" : json["name"], // 处理 name 空值
address: json["address"] == null ? "" : json["address"], // 处理 address 空值
phone: json["phone"] == null ? "" : json["phone"], // 处理 phone 空值
);
Map<String, dynamic> toJson() => {
"\u0024id": id == null ? null : id,
"goods_ref": goodsRef == null ? null : goodsRef,
"loyer": loyer == null ? null : loyer,
"bn_code": bnCode == null ? null : bnCode,
"loyee_no": loyeeNo == null ? null : loyeeNo,
"contact_name": contactName,
"contact_tel": contactTel,
"bn_desc": bnDesc == null ? null : bnDesc,
"req_status": reqStatus == null ? null : reqStatus,
"e_mail": eMail,
"comments": comments == null ? null : comments,
"tender": tender == null ? null : List<dynamic>.from(tender.map((x) => x.toJson())),
"req_date": reqDate == null ? null : reqDate.toIso8601String(),
"ssc_office": sscOffice,
"sn": sn == null ? null : sn,
"name": name == null ? null : name,
"address": address == null ? null : address,
"phone": phone == null ? null : phone,
};
}
class Tender {
Tender({
this.id,
this.goodsRef,
this.inNo,
this.tenderNo,
this.closingDate,
});
final String id;
final int goodsRef;
final int inNo;
final String tenderNo;
final String closingDate;
factory Tender.fromJson(Map<String, dynamic> json) => Tender(
id: json["\u0024id"] == null ? null : json["\u0024id"],
goodsRef: json["goods_ref"] == null ? null : json["goods_ref"],
inNo: json["in_no"] == null ? null : json["in_no"],
tenderNo: json["tender_no"] == null ? null : json["tender_no"],
closingDate: json["closing_date"] == null ? null : json["closing_date"],
);
Map<String, dynamic> toJson() => {
"\u0024id": id == null ? null : id,
"goods_ref": goodsRef == null ? null : goodsRef,
"in_no": inNo == null ? null : inNo,
"tender_no": tenderNo == null ? null : tenderNo,
"closing_date": closingDate == null ? null : closingDate,
};
}注意:
接下来,我们将使用 http 包从 PHP API 获取数据。确保在 pubspec.yaml 文件中添加 http 依赖项:
立即学习“PHP免费学习笔记(深入)”;
dependencies: http: ^0.13.3
然后,创建一个异步函数来获取数据:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
// 假设 email 是从其他地方获取的
String email = "test@example.com";
class MyTableExample extends StatefulWidget {
@override
_MyTableExampleState createState() => _MyTableExampleState();
}
class _MyTableExampleState extends State<MyTableExample> {
Widget myTable = CircularProgressIndicator(); // 初始显示加载指示器
@override
void initState() {
super.initState();
fetchItems(); // 在 initState 中调用 fetchItems
}
Future<void> fetchItems() async {
String apiurl = "YOUR_API_URL"; // 替换为你的 API URL
var response = await http.post(Uri.parse(apiurl), body: {
'username': email //get the username text
});
if (response.statusCode == 200) {
//as wish wish check your response
List<dynamic> decodedJson = jsonDecode(response.body);
List<Model> model = decodedJson.map((item) => Model.fromJson(item)).toList();
print(model.first.bnDesc); // 打印第一个元素的 bnDesc 字段,用于调试
setState(() {
myTable = Table(
//if data is loaded then show table
border: TableBorder.all(width: 1, color: Colors.black45),
children: model.map((nameone) {
return TableRow(
//return table row in every loop
children: [
//table cells inside table row
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.sn ?? ""))),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.name ?? ""))),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.address ?? ""))),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.phone ?? ""))),
],
);
}).toList(),
);
});
} else {
// 处理 API 请求失败的情况
setState(() {
myTable = Text("Failed to load data. Status code: ${response.statusCode}");
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Table Example"),
),
body: Center(
child: myTable, // 显示表格
),
);
}
}代码解释:
现在,我们可以使用 Table 组件来显示从 API 获取的数据。
Table(
border: TableBorder.all(width: 1, color: Colors.black45),
children: model.map((nameone) {
return TableRow(
children: [
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.sn ?? ""), // 使用 ?? "" 处理 null 值
),
),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.name ?? ""), // 使用 ?? "" 处理 null 值
),
),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.address ?? ""), // 使用 ?? "" 处理 null 值
),
),
TableCell(
child: Padding(
padding: EdgeInsets.all(5),
child: Text(nameone.phone ?? ""), // 使用 ?? "" 处理 null 值
),
),
],
);
}).toList(),
);关键点:
通过以上步骤,你已经成功地从 PHP API 获取数据,并将其动态地显示在 Flutter Table 中。 关键在于正确地处理 JSON 数据、定义数据模型,以及使用空值合并运算符来避免空指针异常。 此外,合理的状态管理和错误处理也是保证应用稳定性的重要因素。 请记住替换示例代码中的 YOUR_API_URL 为你实际的 API 地址。
以上就是从 PHP API 获取数据并在 Flutter Table 中显示的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号