flutter - Flutter如何解析JSON数据

标签 flutter dart

我正在编写一种flutter方法,其中我想解析一个简单的JSON数据

{"alm":3,"co2":1,"hu":2,"temp":32,"th":11,"tm":31,"ts":41}
我试图在一个简单的get类中解析它
List data;
  Future<String> getData() async {
    http.Response response = await http.get(
        Uri.encodeFull("http://chicken20.pythonanywhere.com/jsonn"),
        headers: {"Accept": "application/json"});
    print(response.body);
    data = json.decode(response.body);
    print(data);
    return "Success!";
这就是我尝试在Material App中使用的方式
body: new ListView.builder(
          itemCount: data == null ? 0 : data.length,
          itemBuilder: (BuildContext context, int index) {
            return new ListTile(
              leading: const Icon(Icons.stay_primary_portrait),
              title: Text(data.length.toString()),
              subtitle:
              Text('${_deviceData}'),
              trailing: Icon(Icons.more_vert),
              dense: true,
              isThreeLine: true,
            );
          },
        ),
我得到这个错误
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
屏幕上什么也没有显示

最佳答案

首先,来自A​​PI的响应不是json列表,而是一个简单的json对象。
如果要遍历上述对象的键,则可以创建包含所有键的列表,然后使用键索引在响应中获取实际的键名称。

final List<String> keys = ["alm","co2","hu","temp","th","tm","ts"];
那么您可以像下面那样修改您的body小部件-
body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return new ListTile(
            leading: const Icon(Icons.stay_primary_portrait),
            title: Text(data.length.toString()),
            subtitle: Text(data[keys[index]]),
            trailing: Icon(Icons.more_vert),
            dense: true,
            isThreeLine: true,
          );
        },
      ),
希望这可以帮助!

关于flutter - Flutter如何解析JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533880/

相关文章:

flutter - image_picker 插件和 file_picker 插件有什么区别

dart - Flutter:使用 navigator.dart 时断言失败

flutter - 无法将参数类型 'List<String>'分配给参数类型 'List<String>Function()'

dictionary - 在 Flutter 中创建列表映射

http - 如何在flutter http post请求中发送自定义 header

java - Flutter 不是只创建 Java 类,而是 Kotlin

android - 飞镖 : How to return Future<void>

json - 如何将嵌套的 JSON 转换为对象

dart - 使用Polymer-Dart为标签Web组件创建标签标题

firebase - Flutter - 可以在没有 firebase 的情况下使用 Google 登录吗?