Flutter中如何将服务端返回的动态对象数组渲染为表格?
Flutter 动态数组渲染表格实现
核心逻辑说明
- 不需要单独把遍历逻辑写在组件构建外面,直接在表格组件的行生成位置遍历解析好的数组即可
- 选用Flutter原生
DataTable组件实现表格,无需第三方依赖,外层嵌套两层SingleChildScrollView分别处理横向、纵向滚动溢出问题 - 你之前写的for循环存在边界错误:
i <= ress.length会触发数组越界,数组最大下标为length - 1,遍历边界必须用i < ress.length,实际开发中用.map()生成组件列表比手写for循环更简洁
完整可运行代码
直接替换你原来的Report组件代码即可,标记的空白位置直接放滚动包裹的表格组件:
import 'dart:convert'; import 'package:flutter/material.dart'; class Report extends StatelessWidget { // 解析服务端返回的交易数组 final List transactionList = json.decode(MyApp.resultat)['Transactions']; @override Widget build(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( // 就是你标记的空白位置,放以下内容 child: SingleChildScrollView( // 横向滚动适配多列场景 scrollDirection: Axis.horizontal, child: SingleChildScrollView( // 纵向滚动适配多行数据 child: DataTable( // 表头配置,和返回字段一一对应 columns: const [ DataColumn(label: Text('序号')), DataColumn(label: Text('钱包名称')), DataColumn(label: Text('付款手机号')), DataColumn(label: Text('创建时间')), DataColumn(label: Text('金额')), DataColumn(label: Text('币种')), ], // 遍历数组生成每一行数据,不需要提前单独写for循环 rows: transactionList.map<DataRow>((item) { return DataRow( cells: [ DataCell(Text('${item['RowNumber']}')), DataCell(Text('${item['WalletName']}')), DataCell(Text('${item['PayerPhoneNumber']}')), DataCell(Text('${item['CreatedDate']}')), // 金额可以按需格式化,比如保留2位小数:Text((item['Amount'] as double).toStringAsFixed(2)) DataCell(Text('${item['Amount']}')), DataCell(Text('${item['CurrencyCode']}')), ], ); }).toList(), ), ), ), ) ], ), ); } }
额外注意事项
如果
MyApp.resultat是异步请求返回值,必须在JSON解析前加判空逻辑,避免未拿到返回值时调用json.decode报错;如果需要对时间、金额做格式化,直接在对应DataCell的text组件内处理即可。
内容的提问来源于stack exchange,提问作者Daniil
相关产品推荐
相关产品推荐

