【问题标题】:How to populate DataTable with JSON API in flutter如何在 Flutter 中使用 JSON API 填充 DataTable
【发布时间】:2023-04-01 02:53:01
【问题描述】:

我想用从 Internet 获取的数据填写我的表格, 我该怎么做呢

【问题讨论】:

    标签: json flutter api dart


    【解决方案1】:

    试试下面的代码希望对你有帮助。

    创建一个列表和小部件

     List results = [];
      DataRow _getDataRow(index, data) {
        return DataRow(
          cells: <DataCell>[
            DataCell(Text(data['campname'])),//add name of your columns here
            DataCell(Text(data['count'])),
          ],
        );
      }
    

    创建API调用函数:

    Future fetchUsers() async {
      var url = 'Your url here';
      var result = await http.get(url);
      if (result.statusCode == 200) {
        return json.decode(result.body);
      } else {
        throw Exception('Failed');
      }
    }
    

    您的数据表小部件:

      Container(
            child: FutureBuilder(
              future: fetchUsers(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  results = snapshot.data;
                  if (snapshot.data.length != 0) {
                    return Container(
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                      ),
                      child: DataTable(
                        headingRowColor: MaterialStateColor.resolveWith(
                          (states) => Colors.blue[200],
                        ),
                        columnSpacing: 30,
                        columns: [
                          DataColumn(label: Text('Campaigns')),
                          DataColumn(label: Text('Leads')),
                        ],
                        rows: List.generate(
                          results.length,
                          (index) => _getDataRow(
                            index,
                            results[index],
                          ),
                        ),
                        showBottomBorder: true,
                      ),
                    );
                  } else {
                    return Row(
                      children: const <Widget>[
                        SizedBox(
                          // ignore: sort_child_properties_last
                          child: CircularProgressIndicator(),
                          width: 30,
                          height: 30,
                        ),
                        Padding(
                          padding: EdgeInsets.all(40),
                          child: Text('No Data Found...'),
                        ),
                      ],
                    );
                  }
                } else {
                  return Row(
                    children: const <Widget>[
                      SizedBox(
                        // ignore: sort_child_properties_last
                        child: CircularProgressIndicator(),
                        width: 30,
                        height: 30,
                      ),
                      Padding(
                        padding: EdgeInsets.all(40),
                        child: Text('No Data Found...'),
                      ),
                    ],
                  );
                }
              },
            ),
          ),
    

    您的结果屏幕->

    【讨论】:

      【解决方案2】:

      有很多方法,但如果您想要一个简单的解决方案,
      然后你可以使用 json_table 小部件
      https://pub.dev/packages/json_table

      例如

      //Decode your json string
      final String jsonSample='[{"name":"Ram","email":"ram@gmail.com","age":23,"DOB":"1990-12-01"},'
                                    '{"name":"Shyam","email":"shyam23@gmail.com","age":18,"DOB":"1995-07-01"},'
                                    '{"name":"John","email":"john@gmail.com","age":10,"DOB":"2000-02-24"},'
                                    '{"name":"Ram","age":12,"DOB":"2000-02-01"}]';
      var json = jsonDecode(jsonSample);
      //Create your column list
      var columns = [
            JsonTableColumn("name", label: "Name"),
            JsonTableColumn("age", label: "Age"),
            JsonTableColumn("DOB", label: "Date of Birth", valueBuilder: formatDOB),
            JsonTableColumn("age", label: "Eligible to Vote", valueBuilder: eligibleToVote),
          ];
      //Simply pass this column list to JsonTable
      child: JsonTable(json,columns: columns)
      
      //Example of valueBuilder
      String eligibleToVote(value) {
          if (value >= 18) {
            return "Yes";
          } else
            return "No";
      }
      

      如您所见,我们可以显示列的子集。这里我们不显示电子邮件地址,因为我们没有在 columns 变量中添加相关列。

      【讨论】:

      • 我试过了,它显示了一切,但我想显示特定的列
      • 因此您可以将主要数据的子集传递给它。您需要的只是过滤掉主要的 JSON。
      • 你能帮我写一个例子吗?我是 Flutter 新手
      • @HamZa 我加个例子
      猜你喜欢
      • 2018-11-16
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多