【问题标题】:How can we use JSON with datatable?我们如何将 JSON 与数据表一起使用?
【发布时间】:2020-03-03 00:37:32
【问题描述】:

我是 Flutter 的新手,但我努力学习项目所需的一切。

我有一个服务器使用 HTTP 发送的 JSON:

[{"equipe1":"PSG","equipe2":"DIJON","type_prono":"1N2"},{"equipe1":"MONACO","equipe2":"REIMS","type_prono":"1N2"},{"equipe1":"TOULOUSE","equipe2":"RENNES","type_prono":"1N2"},{"equipe1":"MONTPELLIER","equipe2":"STRASBOURG","type_prono":"1N2"},{"equipe1":"AMIENS","equipe2":"METZ","type_prono":"1N2"},{"equipe1":"BREST","equipe2":"ANGERS","type_prono":"1N2"},{"equipe1":"LORIENT","equipe2":"CHAMBLY","type_prono":"1N2"}]

我尝试将其设置为数据表小部件,但操作起来似乎很复杂。

现在这是我的全部代码:

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';

// Create a Form widget.
class Affiche_grille extends StatefulWidget {
  @override
  Affiche_grille_State createState() {
    return Affiche_grille_State();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.

class Affiche_grille_State extends State<Affiche_grille> {
  @override
  final _formKey = GlobalKey<FormState>();

  Grille_display() async {
    // SERVER LOGIN API URL
    var url = 'http://www.axis-medias.fr/game_app/display_grid.php';

    // Store all data with Param Name.
    var data = {'id_grille': 1};

    // Starting Web API Call.
    var response = await http.post(url, body: json.encode(data));

    // Getting Server response into variable.

    var match = json.decode(response.body);

  }

  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    var listmatch = Grille_display();
    return Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DataTable(
              columnSpacing: 20,
              columns: [
                DataColumn(
                  label: Text("Eq 1"),
                  numeric: false,
                  tooltip: "",
                ),
                DataColumn(
                  label: Text("Eq 2"),
                  numeric: false,
                  tooltip: "",
                ),
                DataColumn(
                  label: Text("Type pro"),
                  numeric: false,
                  tooltip: "",
                ),
              ],
              rows: EquipeList.map((equipe_detail) => DataRow(
                  cells: [
                    DataCell(
                      Text(equipe_detail['equipe1'].toString()),
                    ),
                    DataCell(
                      Text(equipe_detail['equipe2'].toString()),
                    ),
                    DataCell(
                      Text(equipe_detail['type_prono'].toString()),
                    ),
                  ]),
              ).toList(),
            )
          ],
        )
    );
  }
}

class Match_detail {
  String equipe1;
  String equipe2;
  String typeProno;

  Match_detail({this.equipe1, this.equipe2, this.typeProno});

  Match_detail.fromJson(Map<String, dynamic> json) {
    equipe1 = json['equipe1'];
    equipe2 = json['equipe2'];
    typeProno = json['type_prono'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['equipe1'] = this.equipe1;
    data['equipe2'] = this.equipe2;
    data['type_prono'] = this.typeProno;
    return data;
  }
}

class EquipeList {
  List<Match_detail> breeds;

  EquipeList({this.breeds});

  factory EquipeList.fromJson(List<dynamic> json) {
    return EquipeList(
        breeds: json
            .map((e) => Match_detail.fromJson(e as Map<String, dynamic>))
            .toList());
  }
}

它不起作用:(它说我:错误:方法'map'没有为类'EquipeList'定义。([flutter_app] lib中的undefined_method

【问题讨论】:

  • 您的问题到底是什么? 你觉得这个 json 怎么样?我觉得很好。
  • 我的问题是我不明白为什么有[开头和结尾],没有必要
  • 你的 JSON 包含一个对象数组,怎么没必要?
  • 一个数组通常包含一些行通常json是一个字符串,我认为我的格式不需要任何数组
  • 我不确定我理解你的意思,你能改写一下吗?

标签: json flutter


【解决方案1】:

您可以在下面复制粘贴运行完整代码
你可以使用包https://pub.dev/packages/json_table

工作演示

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:json_table/json_table.dart';

class SimpleTable extends StatefulWidget {
  @override
  _SimpleTableState createState() => _SimpleTableState();
}

class _SimpleTableState extends State<SimpleTable> {
  final String jsonSample =
      '[{"equipe1":"PSG","equipe2":"DIJON","type_prono":"1N2"},{"equipe1":"MONACO","equipe2":"REIMS","type_prono":"1N2"},{"equipe1":"TOULOUSE","equipe2":"RENNES","type_prono":"1N2"},{"equipe1":"MONTPELLIER","equipe2":"STRASBOURG","type_prono":"1N2"},{"equipe1":"AMIENS","equipe2":"METZ","type_prono":"1N2"},{"equipe1":"BREST","equipe2":"ANGERS","type_prono":"1N2"},{"equipe1":"LORIENT","equipe2":"CHAMBLY","type_prono":"1N2"}]';
  bool toggle = true;

  @override
  Widget build(BuildContext context) {
    var json = jsonDecode(jsonSample);
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: toggle
            ? Column(
          children: [
            JsonTable(
              json,
              showColumnToggle: true,
              tableHeaderBuilder: (String header) {
                return Container(
                  padding: EdgeInsets.symmetric(
                      horizontal: 8.0, vertical: 4.0),
                  decoration: BoxDecoration(
                      border: Border.all(width: 0.5),
                      color: Colors.grey[300]),
                  child: Text(
                    header,
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.display1.copyWith(
                        fontWeight: FontWeight.w700,
                        fontSize: 14.0,
                        color: Colors.black87),
                  ),
                );
              },
              tableCellBuilder: (value) {
                return Container(
                  padding: EdgeInsets.symmetric(
                      horizontal: 4.0, vertical: 2.0),
                  decoration: BoxDecoration(
                      border: Border.all(
                          width: 0.5,
                          color: Colors.grey.withOpacity(0.5))),
                  child: Text(
                    value,
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.display1.copyWith(
                        fontSize: 14.0, color: Colors.grey[900]),
                  ),
                );
              },
              allowRowHighlight: true,
              rowHighlightColor: Colors.yellow[500].withOpacity(0.7),
              paginationRowCount: 20,
            ),
            SizedBox(
              height: 20.0,
            ),
            Text("Simple table which creates table direclty from json")
          ],
        )
            : Center(
          child: Text(getPrettyJSONString(jsonSample)),
        ),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.grid_on),
          onPressed: () {
            setState(
                  () {
                toggle = !toggle;
              },
            );
          }),
    );
  }

  String getPrettyJSONString(jsonObject) {
    JsonEncoder encoder = new JsonEncoder.withIndent('  ');
    String jsonString = encoder.convert(json.decode(jsonObject));
    return jsonString;
  }
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget { 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(      
        primarySwatch: Colors.blue,
      ),
      home: SimpleTable(),
    );
  }
}

【讨论】:

    【解决方案2】:

    我认为您应该首先将此 json 转换为真正的 dart 类,以便更容易使用。您可以在 dart/flutter 中创建一个名为“Equipe”的类并在 json 上运行地图。 [] 表示您正在处理数据列表。

    但如果你不想创建一个类,你绝对可以使用 json 响应,映射到列表。我要尽快给你煮好。 注意:如果还没有完成,请记住也要转换 json。

    DataTable(
        columnSpacing: 20,
        columns: [
        DataColumn(
          label: Text("Eq 1"),
          numeric: false,
          tooltip: "",
        ),
        DataColumn(
          label: Text("Eq 2"),
          numeric: false,
          tooltip: "",
        ),
        DataColumn(
          label: Text("Type pro"),
          numeric: false,
          tooltip: "",
        ),
        ],
        rows: equipeDetails.map((equipeDetail) => DataRow(
                cells: [
                  DataCell(
                    Text(equipeDetail['equipe1'].toString()),
                  ),
                  DataCell(
                    Text(equipeDetail['equipe2'].toString()),
                  ),
                  DataCell(
                    Text(equipeDetail['type_prono'].toString()),
                  ),
                ]),
          ).toList(),
        )
    

    【讨论】:

      【解决方案3】:

      我做到了:

      Grille_display() async {
      // SERVER LOGIN API URL
      var url = 'http://www.axis-medias.fr/game_app/display_grid.php';
      
      // Store all data with Param Name.
      var data = {'id_grille': 1};
      
      // Starting Web API Call.
      var response = await http.post(url, body: json.encode(data));
      
      // Getting Server response into variable.
      
      var match = json.decode(response.body);
      }
      

      我想我需要创建 2 个类,而不是使用 equipeDetailsequipeDetail

      我只需要在表格中显示 equipe1equipe2 并使用类型 prono 来显示单选按钮 1N2 或 12。

      【讨论】:

        【解决方案4】:

        要使用 json 填充数据表,请创建 2 个方法。 一种用于填充列标题。 第二个用于填充行。 然后将方法作为值传递给数据表。

        DataTable(
        columnSpacing: 20,
        columns:
                                                      dataTableColumnHeaderSetter(
                                                          dashBoardItems!
                                                              .oSsummary),
                                                  rows: dashBoardItems!.oSsummary
                                                      .mapIndexed(
                                                        (index, details) => DataRow(
                                                          cells:
                                                              dataTableColumnValueSetter(
                                                                  dashBoardItems!
                                                                      .oSsummary),
                                                        ),
                                                      )
                                                      .toList()),
        

        方法一。

            List<DataColumn> dataTableColumnHeaderSetter(List<OSsummary> summary) {
          return List.generate(summary.length, (i) {
            return DataColumn(
              label: Text(
                summary[i].head,
                textAlign: TextAlign.center,
              ),
              numeric: true,
              tooltip: "",
            );
          });
        }
        

        方法二。

            List<DataCell> dataTableColumnValueSetter(List<OSsummary> summary) {
          return List.generate(summary.length, (i) {
            return DataCell(
              Text(
                summary[i].value,
                textAlign: TextAlign.center,
              ),
              showEditIcon: false,
              placeholder: false,
            );
          });
        }
        

        在未来的构建器中包装数据表并使用 snapshot.data 访问 json 数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-29
          • 2016-03-14
          • 2013-02-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-14
          相关资源
          最近更新 更多