【问题标题】:Get data from JSON and add into the List on initState()从 JSON 获取数据并添加到 initState() 的列表中
【发布时间】:2019-10-04 21:42:30
【问题描述】:

我在下面有 JSON 文件。

Data.json

[{
    "rownum": 1,
    "total": 10.99793271,
    "total2": 106.65666751,
}, {
    "rownum": 2,
    "total": 10.99793271,
    "total2": 106.65666751,
}]

还有class ItemList

List <Item> item;
class Item {
  String row;
  String total;
  String total2;
  Student({this.row, this.total, this.total2});
  }

我如何从data.jsonadd 获取数据到initState() 上的List &lt;Item&gt; item

这样

class MyAppState extends State<MyApp> {
  @override
  void initState() {
  Future<String> _loadAStudentAsset() async {
  return await rootBundle.loadString('assets/data.json');
}
//....some code to add value into list
    super.initState();
  }

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    该解决方案也对您有效:

    Flutter: How to display a short text file from assets on screen of phone?

    如果我们用相同的模板再做一个例子:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart' show rootBundle;
    
    void main() {
      runApp(Test());
    }
    
    class Test extends StatefulWidget {
      @override
      _TestState createState() => _TestState();
    }
    
    class _TestState extends State<Test> {
      Future _future;
    
      Future<String> loadString() async =>
          await rootBundle.loadString('assets/data.json');
    
      @override
      void initState() {
        _future = loadString();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: FutureBuilder(
              future: _future,
              builder: (context, AsyncSnapshot snapshot) {
                if (!snapshot.hasData) {
                  return Text('Loading...');
                }
                List<dynamic> parsedJson = jsonDecode(snapshot.data);
                items = parsedJson.map((element) {
                  return Item(
                    row: element['rownum'].toString(),
                    total: element['total'].toString(),
                    total2: element['total2'].toString(),
                  );
                }).toList();
                ;
    
                return ListView.builder(
                  itemCount: items.length,
                  itemBuilder: (context, index) {
                    final item = items[index];
                    return Column(
                      children: <Widget>[
                        Text(item.row),
                        Text(item.total),
                        Text(item.total2),
                      ],
                    );
                  },
                );
              },
            ),
          ),
        );
      }
    }
    
    List<Item> items;
    
    class Item {
      String row;
      String total;
      String total2;
    
      Item({this.row, this.total, this.total2});
    }
    
    

    【讨论】:

    • 抱歉,我在尝试您的解决方案时收到了flutter: type 'Future&lt;String&gt;' is not a subtype of type 'Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt;'
    • 我更改了代码,再次复制并重建。是的,有一个错误,因为我把它写在一个纯文本上:/
    • 非常感谢。
    【解决方案2】:
    class Item {
      static final String db_row = "rownum";
      static final String db_total = "total";
      static final String db_total2 = "total2";
    
      int row;
      double total;
      double total2;
    
      Item({this.row, this.total, this.total2});
    
      Item.fromMap(Map map) {
        this.row = map[Item.db_row];
        this.total = map[Item.db_total];
        this.total2 = map[Item.db_total2];
      }
    
      Map toMap() =>
          {Item.db_row: row, Item.db_total: total, Item.db_total2: total2};
    
      static List<Item> fromMapList(mapList) {
        List<Item> items = new List();
        new List.from(mapList).forEach((mapItem) {
          items.add(Item.fromMap(mapItem));
        });
        return items;
      }
    }
    

    List <Item> items = Item.fromMapList(await rootBundle.loadString('assets/data.json'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 2023-02-24
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      相关资源
      最近更新 更多