【问题标题】:Dart / Flutter - nested json to data tableDart / Flutter - 嵌套 json 到数据表
【发布时间】:2020-06-17 12:29:27
【问题描述】:

我正在尝试将以下 json 放入数据表 (CFTable)。 json在map>的结构中。我有一个 COA 类来处理内部地图 (Map),以及一个 TransposedCF 类来从该地图 (Map) 制作地图。我不想硬编码外部地图(“Acquisition”、“BP Uplift”...等)或内部地图(“2019”、“2020”...等)的字符串键,因为它会不断变化。我对 TransposedCF 类的 fromJson 方法有困难(因此是?)。

另外,在我建立这个类之后,我想在一个表中使用它,但是那里有很多错误......

JSON:

{
  "Acquisition": {
    "2019": -78600000,
    "2020": 0,
    "2021": 0,
    "2022": 0,
    "2023": 0,
    "2024": 0,
    "2025": 0,
    "2026": 0,
    "2027": 0,
    "2028": 0,
    "2029": 0,
    "2030": 77527013.89465855
  },
  "BP Uplift": {
    "2019": 0,
    "2020": 0,
    "2021": 0,
    "2022": 0,
    "2023": 0,
    "2024": 0,
    "2025": 0,
    "2026": 0,
    "2027": 0,
    "2028": 0,
    "2029": 0,
    "2030": 0
  },
  "Capex": {
    "2019": 0,
    "2020": 0,
    "2021": 0,
    "2022": 0,
    "2023": 0,
    "2024": 0,
    "2025": 0,
    "2026": 0,
    "2027": 0,
    "2028": 0,
    "2029": 0,
    "2030": 0
  }
}

颤动:

import 'package:flutter/material.dart';

class COA {
  final Map<String, double> values;

  const COA({@required this.values});

  factory COA.fromJson(Map json) {
    final values = json['values'];
    return COA(values: values);
  }
}

class TransposedCF {
  final String assetname;
  final Map<String, COA> coas;

  TransposedCF({this.assetname, this.coas});

  factory TransposedCF.fromJson(String name, List json) {
    return TransposedCF(
      assetname: name,
      coas: ?,
    );
  }
}

class CFTable extends StatelessWidget {
  final TransposedCF cf;

  CFTable({Key key, this.cf}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text("OGANICA"),
        DataTable(columns: _buildColumns(), rows: _buildDataRows()),
      ],
    );
  }

  List<DataColumn> _buildColumns() {
    final years = cf.coas.first.values.keys.toList()..sort();
    return [
      DataColumn(label: Text(cf.assetname)),
      for (String year in years) DataColumn(label: Text("$year"))
    ];
  }

  List<DataRow> _buildDataRows() {
    return cf.coas.map<DataRow>((coa) {
      final years = coa.values.keys.toList()..sort();
      return DataRow(cells: [
        DataCell(Text(coa.name)),
        ...years.map<DataCell>((year) {
          final value = coa.values[year];
          //TODO format value
          return DataCell(Text(value.toString()));
        })
      ]);
    }).toList(growable: false);
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第 1 步:使用原始 json 字符串到相关 Map ,在此演示中 class Payload
    第 2 步:将此Payload 传输到年份数据的List
    第三步:使用json_table消费List的年份数据

    工作演示

    代码sn-p

    class Payload {
      Map<String, double> acquisition;
      Map<String, double> bpUplift;
      Map<String, double> capex;
    ...  
    class YearData {
      String year;
      double acquisition;
      double bpUplift;
      double capex;  
    ...  
    void transfer() {
        Payload payload = payloadFromJson(jsonString);
        List<YearData> yearDataList = [];
    
        for (var val in payload.acquisition.keys) {
          var year = val;
          var acquisition = payload.acquisition[val];
          var capex = payload.capex[val];
          var bpUplift = payload.bpUplift[val];
          yearDataList.add(YearData(
              year: year,
              acquisition: acquisition,
              bpUplift: bpUplift,
              capex: capex));
        }
    
        jsonSample = yearDataToJson(yearDataList);
    }  
    

    完整代码

    import 'package:flutter/material.dart';
    import 'dart:convert';
    import 'package:json_table/json_table.dart';
    
    import 'dart:convert';
    
    Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
    
    String payloadToJson(Payload data) => json.encode(data.toJson());
    
    class Payload {
      Map<String, double> acquisition;
      Map<String, double> bpUplift;
      Map<String, double> capex;
    
      Payload({
        this.acquisition,
        this.bpUplift,
        this.capex,
      });
    
      factory Payload.fromJson(Map<String, dynamic> json) => Payload(
            acquisition: Map.from(json["Acquisition"])
                .map((k, v) => MapEntry<String, double>(k, v.toDouble())),
            bpUplift: Map.from(json["BP Uplift"])
                .map((k, v) => MapEntry<String, double>(k, v.toDouble())),
            capex: Map.from(json["Capex"])
                .map((k, v) => MapEntry<String, double>(k, v.toDouble())),
          );
    
      Map<String, dynamic> toJson() => {
            "Acquisition": Map.from(acquisition)
                .map((k, v) => MapEntry<String, dynamic>(k, v)),
            "BP Uplift":
                Map.from(bpUplift).map((k, v) => MapEntry<String, dynamic>(k, v)),
            "Capex": Map.from(capex).map((k, v) => MapEntry<String, dynamic>(k, v)),
          };
    }
    
    List<YearData> yearDataFromJson(String str) =>
        List<YearData>.from(json.decode(str).map((x) => YearData.fromJson(x)));
    
    String yearDataToJson(List<YearData> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class YearData {
      String year;
      double acquisition;
      double bpUplift;
      double capex;
    
      YearData({
        this.year,
        this.acquisition,
        this.bpUplift,
        this.capex,
      });
    
      factory YearData.fromJson(Map<String, dynamic> json) => YearData(
            year: json["year"],
            acquisition: json["Acquisition"],
            bpUplift: json["BPUplift"],
            capex: json["Capex"],
          );
    
      Map<String, dynamic> toJson() => {
            "year": year,
            "Acquisition": acquisition,
            "BPUplift": bpUplift,
            "Capex": capex,
          };
    }
    
    class SimpleTable extends StatefulWidget {
      @override
      _SimpleTableState createState() => _SimpleTableState();
    }
    
    class _SimpleTableState extends State<SimpleTable> {
      String jsonString = '''
      {
      "Acquisition": {
        "2019": -78600000,
        "2020": 0,
        "2021": 0,
        "2022": 0,
        "2023": 0,
        "2024": 0,
        "2025": 0,
        "2026": 0,
        "2027": 0,
        "2028": 0,
        "2029": 0,
        "2030": 77527013.89465855
      },
      "BP Uplift": {
        "2019": 0,
        "2020": 0,
        "2021": 0,
        "2022": 0,
        "2023": 0,
        "2024": 0,
        "2025": 0,
        "2026": 0,
        "2027": 0,
        "2028": 0,
        "2029": 0,
        "2030": 0
      },
      "Capex": {
        "2019": 0,
        "2020": 0,
        "2021": 0,
        "2022": 0,
        "2023": 0,
        "2024": 0,
        "2025": 0,
        "2026": 0,
        "2027": 0,
        "2028": 0,
        "2029": 0,
        "2030": 0
      }
    }
      ''';
      String jsonSample = "";
    
      bool toggle = true;
      List<YearData> yearDataList = [];
    
      @override
      void initState() {
        // TODO: implement initState
        transfer();
        super.initState();
      }
    
      void transfer() {
        Payload payload = payloadFromJson(jsonString);
        List<YearData> yearDataList = [];
    
        for (var val in payload.acquisition.keys) {
          var year = val;
          var acquisition = payload.acquisition[val];
          var capex = payload.capex[val];
          var bpUplift = payload.bpUplift[val];
          yearDataList.add(YearData(
              year: year,
              acquisition: acquisition,
              bpUplift: bpUplift,
              capex: capex));
        }
    
        jsonSample = yearDataToJson(yearDataList);
      }
    
      @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(),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2019-07-04
      • 1970-01-01
      • 2021-05-13
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2014-03-28
      相关资源
      最近更新 更多