从 PHP API 获取数据并在 Flutter Table 中显示

从 php api 获取数据并在 flutter table 中显示

本文档将指导你如何在 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;  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 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.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 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.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 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 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 {  Widget myTable = CircularProgressIndicator(); // 初始显示加载指示器  @override  void initState() {    super.initState();    fetchItems(); // 在 initState 中调用 fetchItems  }  Future 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 decodedJson = jsonDecode(response.body);      List 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 将响应体转换为 List。使用 map 和 Model.fromJson 将 List 转换为 List。使用 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中文网其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1325076.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月12日 11:41:09
下一篇 2025年12月12日 11:41:21

相关推荐

  • PHP中isset()与empty()的最佳实践:有效避免变量未定义警告

    本文详细探讨了在php中如何使用`isset()`和`empty()`函数安全地检查变量,特别是处理`$_post`等超全局变量时,以有效避免`undefined variable`和`undefined index`等常见警告。我们将通过示例代码展示如何编写健壮的php代码,确保变量在使用前已正确…

    2025年12月12日
    000
  • 基于API的城市驾车距离筛选教程

    本文将详细介绍如何高效地根据驾车距离筛选城市列表。文章将阐述为何直接进行网页抓取存在局限性,并推荐转而利用专业的距离计算api(如`distance.to`)作为更可靠、高效的解决方案。我们将通过实际代码示例,指导读者实现从指定“主位置”筛选出75公里内城市的完整流程,并强调api使用的优势、注意事…

    2025年12月12日
    000
  • 使用PHP PDO连接与操作MySQL数据库:完整教程

    本教程详细指导如何在php中使用pdo(php数据对象)安全高效地连接到mysql数据库并执行数据操作。文章涵盖了从建立数据库连接、配置dsn、处理潜在错误,到执行预处理语句进行数据查询和遍历结果的完整流程,旨在帮助开发者掌握利用pdo进行数据库交互的核心技能。 在现代PHP应用开发中,与数据库进行…

    2025年12月12日
    000
  • PHP数值条件分类函数设计与实现:以数据导入为例

    本文将指导您如何设计一个PHP函数,用于根据特定数值范围对数据进行分类,例如将计算结果标记为“好”、“中等”或“差”。通过结合数值计算、格式化和条件判断,此教程提供了一个清晰的解决方案,适用于数据导入等需要动态分类处理的场景。 理解需求:数值分类逻辑 在许多数据处理场景中,我们经常需要根据某个数值的…

    2025年12月12日
    000
  • 解决PHP中Google Chat Bot Webhook失效问题

    本文旨在帮助开发者解决在使用PHP与Google Chat Bot Webhook集成时遇到的“Invalid request token”错误。通过详细的代码示例和步骤说明,我们将深入探讨如何正确配置cURL请求,并提供一些排查问题的技巧,确保你的PHP应用能够成功地向Google Chat发送消…

    2025年12月12日
    000
  • Laravel文件存储:管理公共URL与自定义符号链接

    本教程详细讲解laravel中如何正确配置和访问`storage/app/public`目录下的公共文件,特别是针对子目录文件(如图片)的url问题。文章将介绍laravel默认的`storage:link`机制,并提供通过修改`config/filesystems.php`文件来创建自定义符号链接…

    2025年12月12日
    000
  • PHP数组分段合并:使用不同分隔符实现灵活字符串拼接

    本教程详细介绍了在php中如何对数组进行分段合并,并为不同部分应用不同的字符串分隔符。通过结合`array_chunk`和`implode`函数,开发者可以灵活地将数组的特定元素组合成字符串,满足复杂路径或id拼接的需求,最终实现自定义的字符串输出格式。 在PHP开发中,我们经常需要将数组元素连接成…

    2025年12月12日
    000
  • Symfony 缓存预热后参数读取机制详解

    本文旨在深入解析 Symfony 框架在执行 `cache:warmup` 命令后,参数的处理机制。我们将探讨参数是否仍然从 `parameters.yml` 文件读取,以及它们是否被存储在缓存中。同时,我们还将讨论开发环境和生产环境在参数处理上的差异,帮助开发者更好地理解和管理 Symfony 应…

    2025年12月12日
    000
  • Laravel资源路由中“缺少必要参数”错误的解析与修复

    本文旨在解决Laravel应用中常见的“缺少必要参数”错误,特别是涉及资源路由和隐式模型绑定时。我们将深入分析该错误通常由路由参数名不匹配引起,并提供一套简洁有效的解决方案,确保route()辅助函数、控制器方法参数与路由定义保持一致,从而顺利实现数据编辑等操作。 在Laravel开发中,当我们在使…

    2025年12月12日
    000
  • 解决 Symfony 控制器中实体自动注入(Autowire)失败问题

    本文旨在解决 symfony 控制器中实体参数自动注入失败的常见问题,即当框架尝试将实体类作为服务进行注入时,报错“no such service exists”。我们将探讨其发生原因,并提供一种直接且稳健的解决方案:通过手动从数据库仓库中获取实体,从而绕过自动注入机制,确保控制器能够正确处理实体操…

    2025年12月12日
    000
  • PHP require_once 文件路径错误问题排查与解决方案

    本文针对 PHP 中 `require_once` 函数报错,提示无法打开文件流的问题,提供详细的排查思路和解决方案。通过分析文件路径、利用 `realpath` 函数,以及理解 `require_once` 和 `include_once` 的区别,帮助开发者快速定位并解决此类问题,确保 PHP …

    2025年12月12日
    000
  • PHP命令怎么实现缓存清理_PHP命令行清理缓存与临时文件

    Laravel用php artisan cache:clear等命令清理缓存;2. Symfony用php bin/console cache:clear;3. ThinkPHP可手动清理runtime目录;4. 可编写PHP脚本递归删除缓存文件;5. Linux/macOS下可用php -r执行系…

    2025年12月12日
    000
  • 在Laravel中合并集合并对特定字段进行求和

    本教程将详细介绍如何在laravel中高效地合并两个集合,并根据指定键(如`name`)对特定字段(如`score`)进行聚合求和。通过结合`concat()`、`groupby()`和`map()`等方法,我们将展示如何实现复杂的数据合并逻辑,以获得所需的数据汇总结果,避免直接使用`merge()…

    2025年12月12日
    000
  • PHP正则匹配函数_PHP preg_match等正则函数使用技巧

    答案:PHP中常用preg_match、preg_match_all、preg_replace和preg_split处理字符串;preg_match匹配首个结果,preg_match_all提取所有匹配项,preg_replace支持替换与回调,preg_split按正则分割字符串,合理使用可提升文…

    2025年12月12日
    000
  • phpstorm配置php环境的内置服务器设置

    PhpStorm可通过内置PHP服务器运行调试项目,无需Apache或Nginx。首先配置PHP解释器路径并验证版本,然后右键PHP文件选择Open in Browser启动内置服务器,或通过Run配置自定义端口和路由脚本,服务器随IDE启动关闭,仅限开发使用。 PhpStorm 可以通过内置的 P…

    2025年12月12日
    000
  • TYPO3自定义表单完成器并发执行异常的解析与最佳实践

    在typo3自定义表单完成器中,当多个请求同时执行时,手动通过`generalutility::makeinstance`实例化extbase仓库可能导致`too few arguments`错误,因为extbase仓库的构造函数需要`objectmanagerinterface`参数。本文将深入分…

    2025年12月12日
    000
  • 检查数据库最后四行数据的值

    本文旨在提供一种高效的SQL方法,用于检查数据库表中最后四行数据是否都具有特定值。通过使用子查询和COUNT函数,可以简洁地判断最后四行是否满足条件,避免在应用程序代码中进行循环判断,从而提高性能和代码可读性。 使用SQL高效检查最后N行数据 在数据库操作中,有时需要检查表中最近插入的几行数据是否满…

    2025年12月12日
    000
  • 使用正则表达式提取Meta Description中的数字:一个教程

    本文介绍了如何使用PHP中的`preg_match`函数,通过正则表达式从HTML的Meta Description标签中提取包含千位分隔符的数字。针对不同的Meta Description内容,提供了一个通用的解决方案,并附带详细的正则表达式解释和PHP示例代码。 在网页抓取或数据分析中,经常需要…

    2025年12月12日
    000
  • JavaScript与PHP交互:动态获取后端数据的方法

    本文旨在阐述在javascript(客户端)中安全有效地获取并使用php(服务器端)后端数据的方法。我们将探讨两种主要策略:通过html中的脚本标签直接嵌入数据(适用于初始加载),以及利用ajax进行异步请求以动态获取数据(适用于用户交互或实时更新场景),并提供详细的代码示例和注意事项,以帮助开发者…

    2025年12月12日
    000
  • 如何合并并聚合Laravel集合数据

    本教程详细介绍了如何在Laravel中合并两个集合并对其中特定字段进行聚合。通过利用`concat()`、`groupBy()`和`map()`等核心集合方法,您可以高效地将多个集合连接起来,并根据共同的键对数值型数据进行求和,从而实现复杂的数据转换和汇总,解决`merge()`或`union()`…

    2025年12月12日
    000

发表回复

登录后才能评论
关注微信