我们如何将 JSON 与数据表一起使用?

2024-04-06

我是 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());
  }
}

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


您可以复制粘贴运行下面的完整代码
您可以使用包https://pub.dev/packages/json_table 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(),
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们如何将 JSON 与数据表一起使用? 的相关文章

随机推荐