我有这个自定义数据模型命名为"ServiceModel"
如下:
class ServiceModel {
int status;
String message;
List<dynamic> errors;
Data data;
ServiceModel({
required this.status,
required this.message,
required this.errors,
required this.data,
});
factory ServiceModel.fromJson(Map<String, dynamic> json) => ServiceModel(
status: json["status"],
message: json["message"],
errors: List<dynamic>.from(json["errors"].map((x) => x)),
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"message": message,
"errors": List<dynamic>.from(errors.map((x) => x)),
"data": data.toJson(),
};
}
class Data {
Data({
required this.serviceInfo,
required this.payInfo,
});
ServiceIfo serviceInfo;
PayInfo payInfo;
factory Data.fromJson(Map<String, dynamic> json) => Data(
serviceInfo: ServiceIfo.fromJson(json["serviceIfo"]),
payInfo: PayInfo.fromJson(json["payInfo"]),
);
Map<String, dynamic> toJson() => {
"serviceInfo": serviceInfo.toJson(),
"payInfo": payInfo.toJson(),
};
}
我想用这个函数从我的API得到一个响应:
Future<ServiceModel> getServiceDetail() async {
var url = "${MyStrings.baseUrl}api/providers/profile/ServiceAPI";
var _pref = await SharedPreferences.getInstance();
var header = {
'token': _pref.getString('token'),
};
var response = await http.get(url + '?serviceId=59', headers: header);
print(response.body);
var model = ServiceModel.fromJson((json.decode(response.body)));
print("Model is : $model");
return model;
}
并显示FutureBuilder
,如下所示:
FutureBuilder<ServiceModel>(
future: _service.getServiceDetail(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
print('snapshot: ${snapshot.data}');
return Center(
child: LinearProgressIndicator(
color: Colors.red,
),
);
} else {
return AnimatedSwitcher(
duration: const Duration(seconds: 1),
child: (snapshot.connectionState == ConnectionState.waiting)
? Align(
alignment: Alignment.center,
child: Container(
child: CircularProgressIndicator(
color: parseColor("F8A387"),
),
))
: DetailedServicePager(data: snapshot.data!));
}
},
)
这里一切看起来都很顺利,但它不起作用!!快照返回null,并显示加载指示符
事实上,似乎一切都超过了模型线:
var model = ServiceModel.fromJson((json.decode(response.body)));
行不通! !
我通过将print("Model is : $model");
置于model definition
和return model
之间来证明它
我通过请求添加了一个邮差响应的示例:
{
"status": 200,
"message": "Successful",
"errors": [],
"data": {
"serviceIfo": {
"serviceId": 59,
"customerId": 3,
"providerId": 4,
"parentTitle": [],
"title": "Cleaning",
"price": 90000.0,
"date": "2022/1/1",
"time": "00:45",
"address": "string",
"specialDescription": [
{
"question": "test",
"featureType": 0,
"choice": "test",
"answer": "test"
}
],
"description": "string",
"lat": 0.0,
"lng": 0.0,
"customerFullName": "FirstName LastName",
"custoemrPhoneNumber": "",
"serviceStatus": "Abort Search",
"endTime": "",
"endDate": "",
"serviceCategoryFeaturs": null
},
"payInfo": {
"isPaied": false,
"paymentAmount": 90000.0
}
}
}
所以,当我们在互联网上查找数据(获取数据)时,我们必须使用异步(await和async)技术为了避免任何问题,因为数据需要一些时间来准备显示在我们的小部件上或使用它。
在你的例子中:你用文本发送快照和:
- 如果有数据,它会显示在UI上。
- 如果没有,你会看到加载指示,这就是问题所在!
你必须写一个return语句,在数据加载时返回加载指示符。
要了解更多信息,请阅读这个有用的文档和这个模型。
p。S:这段代码是没有编辑器的,所以你可能会发现一些错误。
FutureBuilder<ServiceModel>(
future: _service.getServiceDetail(),
builder: (context, snapshot) {
if (snapshot.hasError) {
print('snapshot error');
}
if (snapshot.hasData) {
return AnimatedSwitcher(
duration: const Duration(seconds: 1),
child: (snapshot.connectionState == ConnectionState.waiting)
? Align(
alignment: Alignment.center,
child: Container(
child: CircularProgressIndicator(
color: parseColor("F8A387"),
),
))
: DetailedServicePager(data: snapshot.data!));
}
return Center(
child: LinearProgressIndicator(
color: Colors.red,
),
);
},
)
我终于想通了!我的主要错误是在ServiceModel
的映射功能。
response
正常。response.body
有数据,Json.decode(response.body)
返回一个合理的值,然后snapchat
为NULL.
Json.decode
和snapchat
之间唯一未检查的是ServiceModel.fromJson((json.decode(response.body)))
。
依次删除ServiceModel, Data, ServiceInfo, PayInfo的每个字段;我设法找到了问题所在。这是因为我已经定义了一个description
字段,并忘记在我的fromJson(Map<String, dynamic> json)
中定义它。这个小问题导致映射出错因为它被定义了但没有得到任何值它返回null
另一方面,它似乎决定返回null作为整个答案,而不仅仅是可疑字段!