我想处理带有一些错误消息的 http 请求抖动,并在屏幕上将其显示给用户,但我不能这样做。我只是根据建议制作它,但它对我不起作用。请任何人帮助我这是我调用API的函数。
API响应:
{
"code": 1,
"message": "this box is not valid !!",
"data": [],
"error": [],
"status": 400
}
这是功能:
Future<BoxModel> addBox(String boxName, String boxIdentifiant,
String adress_circulation, String proprietaire) async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
Map<String, String> body = {
'boxName': boxName,
'boxIdentifiant': boxIdentifiant,
'adress_circulation': adress_circulation,
'proprietaire': proprietaire,
};
var response = await http.post(Uri.parse(ApiUtil.ADD_BOX),
headers: headers, body: jsonEncode(body));
if (response.statusCode == 200) {
var body = jsonDecode(response.body);
var data = body['message'];
BoxModel box = BoxModel.fromJson(body);
return box;
} else {
throw Exception('Failed to add box');
}
}
void addBox() async {
if (_formKey.currentState.validate()) {
String boxName = _boxNameController.text;
String boxIdentifiant = _boxIdentifiantController.text;
String adress_circulation = _adress_circulationController.text;
String proprietaire = _proprietaireController.text;
BoxModel box = await boxApi.addBox(
boxName, boxIdentifiant, adress_circulation, proprietaire);
if (box != null) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => BoxSettings()));
}
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
我怎样才能在屏幕上显示消息错误?
改变
var body = jsonDecode(response.body);
var data = body['message'];
BoxModel box = BoxModel.fromJson(body);
return box;
到
var body = jsonDecode(response.body);
if(body['error'].isNotEmpty || body['status'] != 200) {
// make error boolean variable true and set in view if true show error message.
} else {
// make error boolean variable false
var data = body['message'];
BoxModel box = BoxModel.fromJson(body);
return box;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句