0

0

从 PHP API 获取数据并填充 Flutter 表格

DDD

DDD

发布时间:2025-10-18 09:05:00

|

949人浏览过

|

来源于php中文网

原创

从 php api 获取数据并填充 flutter 表格

本文档旨在指导开发者如何从 PHP API 获取数据,并使用 Flutter 的 Table 组件将数据动态地填充到表格中。文章将涵盖数据模型的定义、API 数据的获取、JSON 解析以及表格的构建,同时提供代码示例和注意事项,帮助开发者解决常见的 NoSuchMethodError 问题。

数据模型定义

首先,我们需要定义一个 Dart 类来映射从 PHP API 获取的 JSON 数据。根据提供的 JSON 示例,我们已经有了 Model 和 Tender 类。确保这些类中的字段类型与 API 返回的数据类型一致。例如,如果 API 返回的某个字段可能为 null,则在 Dart 类中将其声明为可空类型(例如 String? 或 dynamic)。

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,
  });

  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;

  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.tryParse(json["req_date"]),
    sscOffice: json["ssc_office"],
  );

  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,
  };
}

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,
  };
}

注意:

  • 将可能为 null 的字段类型改为可空类型,例如 String?。
  • 使用 DateTime.tryParse 来解析日期字符串,避免解析失败。
  • 在 toJson 方法中,对可空列表进行非空判断。

从 PHP API 获取数据

使用 http 包从 PHP API 获取数据。确保已在 pubspec.yaml 文件中添加了 http 依赖。

立即学习PHP免费学习笔记(深入)”;

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.5 # 确保使用最新版本

然后,可以使用以下代码从 API 获取数据:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<List<Model>> fetchItems(String email) async {
  String apiurl = "YOUR_API_ENDPOINT"; // 替换为你的 API 端点
  var response = await http.post(Uri.parse(apiurl), body: {
    'username': email //get the username text
  });

  if (response.statusCode == 200) {
    // 使用 utf8.decode 处理中文乱码问题
    final decodedBody = utf8.decode(response.bodyBytes);
    List<dynamic> jsonResponse = jsonDecode(decodedBody);
    List<Model> model = jsonResponse.map((item) => Model.fromJson(item)).toList();
    return model;
  } else {
    throw Exception('Failed to load data from API');
  }
}

注意:

  • 将 YOUR_API_ENDPOINT 替换为你的实际 API 端点。
  • 使用 utf8.decode(response.bodyBytes) 处理中文乱码问题。
  • 使用 Model.fromJson(item) 将 JSON 数据转换为 Model 对象。
  • 添加错误处理,当 API 请求失败时抛出异常。

构建 Flutter 表格

获取到数据后,就可以使用 Table 组件来显示数据。

Cardify卡片工坊
Cardify卡片工坊

使用Markdown一键生成精美的小红书知识卡片

下载
import 'package:flutter/material.dart';

class MyTable extends StatefulWidget {
  final String email;

  const MyTable({Key? key, required this.email}) : super(key: key);

  @override
  _MyTableState createState() => _MyTableState();
}

class _MyTableState extends State<MyTable> {
  late Future<List<Model>> _dataFuture;

  @override
  void initState() {
    super.initState();
    _dataFuture = fetchItems(widget.email);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Data Table')),
      body: FutureBuilder<List<Model>>(
        future: _dataFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (snapshot.hasData) {
            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Table(
                border: TableBorder.all(width: 1, color: Colors.black45),
                columnWidths: const {
                  0: IntrinsicColumnWidth(),
                  1: IntrinsicColumnWidth(),
                  2: IntrinsicColumnWidth(),
                  3: IntrinsicColumnWidth(),
                },
                children: [
                  // 表头
                  TableRow(
                    children: [
                      TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: const Text('Goods Ref')))),
                      TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: const Text('Loyer')))),
                      TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: const Text('BN Code')))),
                      TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: const Text('BN Desc')))),
                    ],
                  ),
                  // 表格数据
                  ...snapshot.data!.map((item) {
                    return TableRow(
                      children: [
                        TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: Text(item.goodsRef?.toString() ?? '')))),
                        TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: Text(item.loyer ?? '')))),
                        TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: Text(item.bnCode ?? '')))),
                        TableCell(child: Center(child: Padding(padding: const EdgeInsets.all(8.0), child: Text(item.bnDesc ?? '')))),
                      ],
                    );
                  }).toList(),
                ],
              ),
            );
          } else {
            return const Center(child: Text('No data available'));
          }
        },
      ),
    );
  }
}

关键点:

  • 使用 FutureBuilder 来处理异步数据加载。
  • 在 Text 组件中使用 item.propertyName ?? '' 来处理可能为 null 的值,避免 NoSuchMethodError。
  • 使用 SingleChildScrollView 包裹 Table 组件,以支持水平滚动。
  • 添加表头,使表格更易于理解。
  • 使用 IntrinsicColumnWidth 可以让单元格根据内容自动调整宽度。

解决 NoSuchMethodError

NoSuchMethodError: The getter 'length' was called on null 错误通常发生在尝试访问 null 值的属性时。例如,如果 nameone.sn 为 null,则 nameone.sn.length 会抛出此错误。

解决方法是在访问可能为 null 的属性之前,使用空值检查或空值合并运算符 ??。例如:

Text(nameone.sn ?? "") // 如果 nameone.sn 为 null,则显示空字符串

或者,可以使用条件判断:

Text(nameone.sn != null ? nameone.sn : "")

在上面的代码示例中,我们已经使用了空值合并运算符 ?? 来处理可能为 null 的值,从而避免了 NoSuchMethodError。

总结

本文档详细介绍了如何从 PHP API 获取数据并在 Flutter 中使用 Table 组件显示数据。通过定义数据模型、使用 http 包获取数据、解析 JSON 数据以及使用空值合并运算符处理 null 值,可以有效地构建动态表格并避免常见的错误。记住,在处理 API 数据时,始终要考虑数据可能为 null 的情况,并采取相应的措施来避免运行时错误。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

457

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

549

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

337

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

82

2025.09.10

数据类型有哪几种
数据类型有哪几种

数据类型有整型、浮点型、字符型、字符串型、布尔型、数组、结构体和枚举等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

338

2023.10.31

php数据类型
php数据类型

本专题整合了php数据类型相关内容,阅读专题下面的文章了解更多详细内容。

225

2025.10.31

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

138

2026.02.12

string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1051

2023.08.02

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP课程
PHP课程

共137课时 | 13.6万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 11.3万人学习

PHP新手语法线上课程教学
PHP新手语法线上课程教学

共13课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号