【问题标题】:Json got parsed but the cannot display the data in the UI flutter [SOLVED]Json 已解析,但无法在 UI 中显示数据颤动 [已解决]
【发布时间】:2021-09-21 08:22:45
【问题描述】:

我试图从 REST API 获取数据结果,然后将其显示在 UI 中。所以一切都很顺利,JSON 被很好地解析,try 和 catch 方法工作正常。但不知何故,代码无法在 UI 中显示解析结果。都没有给我错误或异常。在过去的几天里,我一直在努力达到预期的结果。

模型类:

 import 'dart:convert';

Transaction transactionFromJson(String str) =>
    Transaction.fromJson(json.decode(str));

String transactionToJson(Transaction data) => json.encode(data.toJson());

class Transaction {
  Transaction({
    required this.dataDescription,
    required this.orderStatus,
    required this.statusObjects,
  });

  String dataDescription;
  String orderStatus;
  List<StatusObject> statusObjects;

  factory Transaction.fromJson(Map<String, dynamic> json) => Transaction(
        dataDescription: json["data-description"],
        orderStatus: json["order-status"],
        statusObjects: List<StatusObject>.from(
            json["status-objects"].map((x) => StatusObject.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data-description": dataDescription,
        "order-status": orderStatus,
        "status-objects":
            List<dynamic>.from(statusObjects.map((x) => x.toJson())),
      };
}

class StatusObject {
  StatusObject({
    required this.type,
    required this.status,
    required this.date,
    required this.time,
  });

  String type;
  String status;
  DateTime date;
  String time;

  factory StatusObject.fromJson(Map<String, dynamic> json) => StatusObject(
        type: json["type"],
        status: json["status"],
        date: DateTime.parse(json["date"]),
        time: json["time"],
      );

  Map<String, dynamic> toJson() => {
        "type": type,
        "status": status,
        "date": date.toIso8601String(),
        "time": time,
      };
}

This is how the JSON looks like:

    {
        "data-description": "This api will return an array of objects to be placed in the order status timeline on the second screen",
        "order-status": "Success",
        "status-objects": [
            {
                "type": "Payment",
                "status": "completed",
                "date": "2021-07-02T00:00:00",
                "time": "12:00AM"
            },
            {
                "type": "Units Allocated",
                "status": "by Axis",
                "date": "2021-07-13T00:00:00",
                "time": "12:00AM"
            }
        ]
    }

进行解析和获取的API_Manager服务类

class API_Manager {
  static Future<Transaction> getDetails() async {
    var client = http.Client();
    var transactions;
    try {
      var response = await client.get(
          Uri.https("your api url here"));

      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = jsonDecode(jsonString);
        transactions = Transaction.fromJson(jsonMap);
      }
    } catch (e) {
      return transactions;
    }
    return transactions;
  }
}

我想要显示解析后的 JSON 的 UI 组件:

代码

FutureBuilder<Transaction>(
                  future: API_Manager.getDetails(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      var data = snapshot.data!.statusObjects;
                      return ListView.builder(
                        itemCount: data.length,
                        itemBuilder: (context, index) =>
                            Text('$index : ${data[index].status}'),
                      );
                    }
                    return Text('Something was wrong!');
                  },
                ),

我得到的输出是“出了点问题”

我很确定我遗漏了一小段代码来使它工作。我已经在这段代码上工作了好几天,但无法做到。我请求你们,请帮助我获得结果或指出我遗漏的代码。

如果您能以任何可能的方式帮助我,我们将不胜感激。

【问题讨论】:

  • 打印出response.body。你得到什么价值?
  • 是的,我得到了 json 输出
  • 你得到了什么statusCode
  • 嘿!我已经更新了代码。此外,我对在代码中集成 REST API 还是很陌生。所以我请求你是否可以帮我解决这个问题@JohnJoe
  • 首先我们需要知道if块是否被执行。请打印出response.statusCode。你得到什么价值?

标签: json flutter dart flutter-widget


【解决方案1】:

试试这个

var response = await client
          .get(Uri.https("domain", "accounts/test-data/"));

var response = await http
      .get(Uri.parse("domain/accounts/test-data/"));


这个不起作用可能是因为主域部分不应该使用/,因为它表示子路径,

      var response = await client
          .get(Uri.https("domain/accounts", "test-data/"));

【讨论】:

  • 虽然我在打印声明中得到了响应正文。但我仍在努力获得对 UI 的响应。请你看看我遇到的错误
  • 我没有遇到 UI 问题,你能分享一下吗?如果 (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(); 可能你可以试试 'FutureBuilder' ``` if (snapshot.hasData) { ......... ``` 那么
  • 嘿!如果您能从解决方案中删除 API URL,将不胜感激。
  • 嘿!如果您能看看我面临的这个问题,将不胜感激stackoverflow.com/questions/68603763/…
  • 嘿!你能帮我解决一个问题吗? stackoverflow.com/questions/68863386/…
猜你喜欢
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2014-10-05
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
相关资源
最近更新 更多