定义Future时如下:
Future<HttpRequest> httpRequest = HttpRequest.request(url,
method: method, requestHeaders: requestHeaders);
Run Code Online (Sandbox Code Playgroud)
我想在5个secondes之后处理超时.我正在写这样的代码:
httpRequest.timeout(const Duration (seconds:5),onTimeout : _onTimeout());
Run Code Online (Sandbox Code Playgroud)
我的超时功能是:
_onTimeout() => print("Time Out occurs");
Run Code Online (Sandbox Code Playgroud)
根据Future timeout()方法文档,如果onTimeout省略,则超时将导致返回的future用a完成TimeoutException.但是使用我的代码,我的方法_onTimeout()被正确调用(但是立即,不是在5秒之后),我总是得到一个
5秒后的TimeException ...(0:00之后的TimeoutException:05.000000:未来未完成)
我错过了什么吗?
我想为网络实用程序创建单独的类。网络实用程序将具有像 isNetworkAvailable() 这样的方法,我可以在每个请求之前使用它。
我使用此代码检查互联网。我也将此函数包装到 initState 中。当互联网不可用时,小吃吧总是显示。但是连接到互联网后,小吃店并没有消失。我不能使用连接插件,因为他们说在 Android 上,该插件不保证连接到 Internet。
checking1(TextEditingController usernameController, BuildContext context,
String _url, GlobalKey<ScaffoldState> _scaffoldKey) async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
usernameController.text == '' ?
showDialog(...some code...) :
usernameValidation(usernameController.text, context, _url);
}
}
on SocketException
catch (_) {
_showSnackBar(_scaffoldKey);
}
}
Run Code Online (Sandbox Code Playgroud) 我正在寻找检查设备是否从 Flutter iOS 和 Android 应用程序连接到互联网的最佳方法。正如官方文档中所述, connectivity_plus还不够:
请注意,在 Android 上,这并不能保证连接到互联网。例如,应用程序可能可以访问 WiFi,但它可能是无法访问的 VPN 或酒店 WiFi。
我还发现了一个老问题,建议一些“手工制作”的解决方法,但该线程太旧了,因为我们现在已经是 2023 年了。有没有新的方法来检查连接状态?您如何在应用程序中处理它?
这可能是一个菜鸟问题,但是如果用户没有互联网连接或者获取数据需要很长时间,我该如何让我的响应抛出异常?
Future<TransactionModel> getDetailedTransaction(String crypto) async {
//TODO Make it return an error if there is no internet or takes too long!
http.Response response = await http.get(crypto);
return parsedJson(response);
}
Run Code Online (Sandbox Code Playgroud) 你如何持续检查互联网访问?我能够显示是否已连接 wifi 或移动数据。但是,并非所有连接都可以访问 Internet。
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
}
Run Code Online (Sandbox Code Playgroud)
这是我目前使用的代码。我希望有人可以连续检查互联网访问?