在DataTable中使用FutureBuilder的snapshot.data

时间:2021-04-26 09:09:20

标签: flutter http dart datatable

我是 Flutter 的新手,我一直在 Flutter DataTable 小部件中显示数据。

我试图找到在 DataTable 中使用 http 数据的最简单方法。如果可能的话,我会避免为此操作创建 Dart 类,因为 - 看起来 - FutureBuilder 的 snapshot.data 与我的“testData”相同,它完美地出现在表中。感谢您的建议。

这是我的示例代码:

fetchData() async {
  final response = await http.get(Uri.https('test.url', 'test/test'));

  if (response.statusCode == 200) {

    var jsonData = json.decode(response.body);
    return jsonData;

  } else {
    throw Exception('Failed to load data');
  }
}

    FutureBuilder(
        future: fetchData(),
        builder: (context, snapshot) {

          if (snapshot.hasData) {

            var fetchedData = snapshot.data;

            var testData = [
              {"Desc": "Desc 1.", "Code": "AB"},
              {"Desc": "Desc 2.", "Code": "AC"},
              {"Desc": "Desc 3.", "Code": "AD"},
            ];

            // fetchedData and testData seemingly the same in the console
            print(fetchedData);
            print(testData);

            return DataTable(
                    columns: [
                      DataColumn(label: Text('Description')),
                      DataColumn(label: Text('Code')),
                    ],
                    sortColumnIndex: 1,
                    rows:
                    fetchedData // it works with "testData" but not with "fetchedData"
                        .map(
                      ((element) => DataRow(
                        cells: <DataCell>[
                          DataCell(Text(element['Desc'])),
                          DataCell(Text(element['Code'])),
                        ],
                      )),
                    ).toList(),
                  );
          } else {
            // We can show the loading view until the data comes back.
            debugPrint('Step 1, build loading widget');
            return CircularProgressIndicator();
          }
        },
      );

0 个答案:

没有答案