繁体   English   中英

我正在尝试在列表视图中显示我的 JSON 响应。 颤振/飞镖

[英]I am trying to display my JSON response in a List View. Flutter/Dart

这是获取响应并将其存储在缓存中的代码:

onPressed: () async{

                    var newMessage = await (ReadCache.getString(key: 'cache1'));

                      var response = await http.get(
                        Uri.parse(
                            'http://192.168.1.8:8080/HongLeong/MENU_REQUEST.do?_dc=1657717579436&table_id=25018&fk_table_id=25004&id_MenuAction=3&reset_context=1&ViewType=MENU_REQUEST&gui_open_popup=1&id_Window=5&activeWindowId=mw_5&noOrigUserDate=true&LocalDate=20220713&LocalTime=21061900&TimeZone=Asia/Shanghai&UserDate=0&UserTime=0&server_name=OPRISK_DATACOLLECTOR&key_id_list=&cell_context_id=0&id_Desktop=100237&operation_key=1000007&operation_sub_num=-1&is_json=1&is_popup=0&is_search_window=0&ccsfw_conf_by_user=0&is_batch=0&previousToken=1657717554097&historyToken=1657717579434&historyUrl=1'),
                        headers: {HttpHeaders.cookieHeader: newMessage},
                      );
                      ResponseModel responseModel =
                      ResponseModel.fromJson(jsonDecode(response.body));

                    final listNode = responseModel.response.genericListAnswer.listNode;

                    Map<String, dynamic> tableMessages = {
                      for (final json in listNode.map((x) => x.toJson()).where((json) => json['field'][5]['field_value'] == 'Loss Event'))
                        "Message": json['field'][0]['field_value'],
                    };

                    await WriteCache.setString(key: 'cache3', value: tableMessages['Message']);
                    print(tableMessages);

                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) =>  messageBoard()));

                    }

我正在成功打印预期的消息:

I/flutter (27053): {Message: There are 1 Loss Event currently in the status LE110 - Pending Approval}

但这是我在设备上看到的: 在此处输入图像描述

这是显示列表的代码:

body: Row(
        children: [
          Expanded(
            child: FutureBuilder(
              future: ReadCache.getString(key: "cache3"),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: ListTile(
                            title: Text(
                                snapshot.data[index],
                              style: GoogleFonts.poppins(
                                textStyle : const TextStyle(
                                  fontWeight: FontWeight.normal,
                                  fontSize: 20,
                                ),
                              )
                            ),
                            tileColor: Colors.blueGrey[200],
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      });
                } else {
                  return const Text("No Data");
                }
              },
            ),
          ),
        ],
      ),

如何正常显示响应,而不是像提供的图像中那样显示单独的元素? 谢谢。

cache3只存储一个字符串,即Message字符串。 itemCount属性中, Message字符串的长度被指定为项目数。 只需将其更改为1并更改它访问文本的方式。

它将如下所示:

body: Row(
        children: [
          Expanded(
            child: FutureBuilder<String>(
              future: ReadCache.getString(key: "cache3"),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return ListView.builder(
                      itemCount: 1,                     // <- Here
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.all(5.0),
                          child: ListTile(
                            title: Text(
                              snapshot.data,            // <- Here
                              style: GoogleFonts.poppins(
                                textStyle : const TextStyle(
                                  fontWeight: FontWeight.normal,
                                  fontSize: 20,
                                ),
                              )
                            ),
                            tileColor: Colors.blueGrey[200],
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      });
                } else {
                  return const Text("No Data");
                }
              },
            ),
          ),
        ],
      ),

另一方面,如果打算有多个消息,则应该更改它们的填充方式,因为最后一个总是获胜。

    List<String> messages = [
      for (final json in listNode
          .map((x) => x.toJson())
          .where((json) => json['field'][5]['field_value'] == 'Loss Event'))
        json['field'][0]['field_value'],
    ];

并将其保存/恢复为字符串列表:

await WriteCache.setStringList(key: 'cache3', value: messages);
    future: ReadCache.getStringList(key: "cache3")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM