我遇到了这个奇怪的异常,它不断出现并冻结我的应用程序。
我尝试使用提供程序包处理 http 包中的SocketException和TimeOutException 。
class Auth with ChangeNotifier{
..........
Future<User> getUser(String id) async {
try {
final user = (await http.post("${Domain.ADDRESS}/user",
headers: {"auth-token": _token}, body: {"userId": id}))
.body;
} on SocketException {
throw HttpException("DISCONNECTED");
} on TimeoutException {
throw HttpException("TIMEOUT");
} catch (error) {
print(error);
throw HttpException("SOMETHING_WENT_WRONG");
}
notifyListeners();
return userdata;
}
......
}
当互联网在未连接的应用程序中冻结时
on SocketException {
throw HttpException("DISCONNECTED"); <------------ Exception has occurred.
HttpException (DISCONNECTED)
但我在下一个屏幕上处理这个
@override
Future<void> didChangeDependencies() async {
......
setState(() {
isLoading = true;
});
try{
user= await Provider.of<Auth>(context)
.getUser(Provider.of<Auth>(context).userId);
if (this.mounted) {
setState(() {
isLoading = false;
});
}
}on HttpException catch(error){
if(error.toString().contains("DISCONNECTED")){
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Please check your internet
connection"),));
}
}catch(error){
print(error);
}
super.didChangeDependencies();
}
自定义 HttpException.dart
class HttpException implements Exception {
final String message;
HttpException(this.message);
@override
String toString() {
return message;
}
}