【发布时间】: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