我在异常处理方面遇到了问题,我构建了产品管理器应用程序,在该应用程序中,我使用firebase rest API将数据发布到服务器,如果偶然发生任何错误,则使用异常,然后重定向到主屏幕。但是,如果出现任何错误,它将只显示加载微调器,那么这里的问题是什么,并告诉它异常和未来是如何工作的?
如果url中有问题,它将显示警告对话框并显示错误消息,之后将显示加载微调器,但根据catchError之后的代码,它将返回future,这意味着接下来应该运行块内容,但这不起作用,那么这背后的行为是什么?
具有后置方法的函数
Future<void> addProduct(Product product) {
const url =
'';
return http
.post(
Uri.parse(url),
body: json.encode(
{
'title': product.title,
'description': product.description,
'price': product.price,
'imageUrl': product.imageUrl,
'isFavorite': product.isFavorite,
},
),
)
.then(
(response) {
final id = json.decode(response.body)['name'];
final newProduct = Product(
id: id,
title: product.title,
description: product.description,
price: product.price,
imageUrl: product.imageUrl,
);
_items.add(newProduct);
notifyListeners();
},
).catchError(
(error) {
print(error.toString());
throw error;
},
);
}
前面使用的代码
Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct)
.catchError((error) {
return showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
title: const Text('An Error Occured!!'),
content: const Text('Something went wrong'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Okay'),
)
],
);
});
}).then((_) {
setState(() {
_isLoding = false;
});
Navigator.of(context).pop();
});
}
}