本文档将指导你如何在 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, };}登录后复制
注意:
dynamic 类型用于处理 API 返回的可能为 null 的字段。fromJson 工厂方法用于将 JSON 数据转换为 Model 对象。在model类中添加了sn, name, address, phone字段,用于表格展示。从 API 获取数据
接下来,我们将使用 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, // 显示表格 ), ); }}导入必要的包: 导入 dart:convert 用于 JSON 转换,http 用于 API 请求,以及 flutter/material.dart 用于 Flutter 组件。fetchItems() 函数:使用 http.post 发送 POST 请求到指定的 API URL。如果响应状态码为 200 (OK),则解析 JSON 响应。使用 jsonDecode 将响应体转换为 Listzuojiankuohaophpcndynamic>。使用 map 和 Model.fromJson 将 List<dynamic> 转换为 List<Model>。使用 setState 更新 myTable 变量,这将触发 UI 重新构建。在 setState 中,创建一个 Table 组件,并使用 model.map 动态生成 TableRow。使用 ?? "" 处理可能为空的字段,确保在 Text 组件中显示空字符串而不是 null。错误处理: 添加了对 API 请求失败情况的处理,如果状态码不是 200,则显示错误消息。initState: 在initState中调用fetchItems()方法,在页面初始化时加载数据。CircularProgressIndicator: 初始时显示加载指示器,直到数据加载完成。Scaffold: 使用Scaffold构建基本页面结构,包括AppBar和包含表格的body。
在 Flutter Table 中显示数据
现在,我们可以使用 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(),);登录后复制
关键点:
使用 TableBorder.all 定义表格边框样式。使用 model.map 遍历数据列表,并为每个数据项创建一个 TableRow。在 Text 组件中使用 ?? "" 空值合并运算符,以确保在字段为 null 时显示空字符串,避免 NoSuchMethodError 错误。总结
通过以上步骤,你已经成功地从 PHP API 获取数据,并将其动态地显示在 Flutter Table 中。 关键在于正确地处理 JSON 数据、定义数据模型,以及使用空值合并运算符来避免空指针异常。 此外,合理的状态管理和错误处理也是保证应用稳定性的重要因素。 请记住替换示例代码中的 YOUR_API_URL 为你实际的 API 地址。
以上就是从 PHP API 获取数据并在 Flutter Table 中显示的详细内容,更多请关注php中文网其它相关文章!