【问题标题】:How to transform JSON data into an objet to use it later into a table?如何将 JSON 数据转换为对象以便稍后将其用于表中?
【发布时间】:2020-01-29 16:56:00
【问题描述】:

我有一个StreamBuilder,它每秒都会给我一个 JSON。我有一个名为“fichajes”的类,它们的属性是:id, worker_id, date, hour, type_checking_id

JSON 是:

{
  "fichajes": [
    {
      "id": 310,
      "worker_id": 1,
      "date": "30/09/2019",
      "hour": "11:07:04",
      "type_checking_id": 2,
      "zone_checking_id": null
    }
  ]
}

我想获取一个 json 对象,以便稍后在表格中使用它。

StreamBuilder(
      initialData: Center(
        child: new CircularProgressIndicator(),
      ),
      stream: _someData(),
      builder: (context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState != ConnectionState.done ||
            snapshot.hasError) {
          return ListView.builder(
            itemCount: 1,
            itemBuilder: (BuildContext context, int index) {
              final Fichajes fichaje = snapshot.data;
              return ListTile(
                title: Text("titulo" + fichaje.fichajes[index].id.toString()),
                subtitle: Text("subtitulo"),
              );
            },
          );
        } else {
          return Center(child: LinearProgressIndicator());
        }
      },
    );

Stream<Widget> _someData() async* {
    yield* Stream.periodic(
      Duration(seconds: 1),
      (int a) {

        //save into a general variable "allInfo" response from json
        loadUser(); 

        print("_someData");
        return getInfo();
      },
    );
  }

getInfo() {
    return new Container(
      child: new Text(allInfo.toString()),
    );
}

【问题讨论】:

    标签: json flutter stream-builder


    【解决方案1】:

    你可以像这样转换你的输出:

     Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
    

    如果你想使用podo类,那么你应该看看里面 quicktype

    【讨论】:

      【解决方案2】:

      您首先需要使用 dart:convert 核心库中的 json 帮助程序反序列化 JSON。然后您可以访问decodedJsonObject['fichajes'][index]['id'] 之类的数据,或者创建一个类以使用.fromJson(Map&lt;String, dynamic&gt; json) 工厂构造函数进一步反序列化decodedJsonObject,以将其解码为更易于使用的静态类型类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-09
        • 1970-01-01
        • 2021-06-12
        • 2021-12-22
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 2011-03-17
        相关资源
        最近更新 更多