You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中实现类似示例图的动态数据表格结构?

Flutter 动态数据表格实现方案

核心思路

利用Flutter内置的DataTable组件,通过动态生成DataColumn(列)和DataRow(行)适配动态数据源,只需将数据源与列配置关联,即可实现灵活的动态表格。

代码实现

1. 定义数据模型(也可直接用Map存储数据)

class TableItem {
  final String id;
  final String name;
  final int quantity;
  final double price;

  TableItem({
    required this.id,
    required this.name,
    required this.quantity,
    required this.price,
  });
}

2. 封装动态表格组件

class DynamicDataTable extends StatelessWidget {
  final List<TableItem> data;
  final Map<String, String> columnConfig; // 键:数据字段名,值:列标题

  const DynamicDataTable({
    super.key,
    required this.data,
    required this.columnConfig,
  });

  @override
  Widget build(BuildContext context) {
    // 生成表格列
    List<DataColumn> _generateColumns() {
      return columnConfig.entries.map((entry) {
        return DataColumn(
          label: Text(entry.value),
          numeric: entry.key == 'quantity' || entry.key == 'price', // 数字列自动右对齐
        );
      }).toList();
    }

    // 生成表格行
    List<DataRow> _generateRows() {
      return data.map((item) {
        return DataRow(cells: [
          DataCell(Text(item.id)),
          DataCell(Text(item.name)),
          DataCell(Text(item.quantity.toString())),
          DataCell(Text('\$${item.price.toStringAsFixed(2)}')),
        ]);
      }).toList();
    }

    // 横向滚动适配窄屏
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: DataTable(
        columns: _generateColumns(),
        rows: _generateRows(),
        border: TableBorder.all(color: Colors.grey.shade300),
        headingRowColor: MaterialStateProperty.all(Colors.grey.shade100),
      ),
    );
  }
}

3. 使用动态表格

class TableDemoScreen extends StatelessWidget {
  // 模拟动态加载的数据源
  final List<TableItem> mockData = [
    TableItem(id: '001', name: '商品A', quantity: 5, price: 19.99),
    TableItem(id: '002', name: '商品B', quantity: 2, price: 29.99),
    TableItem(id: '003', name: '商品C', quantity: 8, price: 9.99),
  ];

  // 自定义列配置
  final columnConfig = {
    'id': 'ID',
    'name': '商品名称',
    'quantity': '数量',
    'price': '单价',
  };

  TableDemoScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('动态数据表格')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: DynamicDataTable(
          data: mockData,
          columnConfig: columnConfig,
        ),
      ),
    );
  }
}

扩展优化

如果需要适配任意结构的动态数据,可将TableItem替换为Map<String, dynamic>,并修改行生成逻辑:

// 修改组件接收的数据源类型
final List<Map<String, dynamic>> data;

// 动态生成单元格
List<DataCell> _generateCells(Map<String, dynamic> item) {
  return columnConfig.keys.map((key) {
    return DataCell(Text(item[key].toString()));
  }).toList();
}

// 生成行时调用
return DataRow(cells: _generateCells(item));

这样无论数据源字段如何变化,只需更新columnConfig即可适配新的列结构。

内容的提问来源于stack exchange,提问作者user20076241

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:45:48