我想在每5秒的时间间隔内检查一下我的颤音应用程序的互联网连接。
发布于 2022-08-05 14:28:10
要检查internet连接,您可以这样使用dart:io:
import 'dart:io;'
Future<bool> checkInternetConection() async {
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
return false;
}如果您有互联网连接,将返回true,如果没有,则返回false。否则,你能更具体的间隔为5秒吗?
发布于 2022-08-05 15:13:09
您可以将Ariel的答案与Timer.periodic结合使用,如下所示:
bool isConnected = false;
Future<bool> checkInternetConnection() async {
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
return false;
}
@override
Widget build(BuildContext context) {
Timer.periodic(const Duration(seconds: 5), (timer) {
checkInternetConnection().then((value) {
setState(() {
isConnected = value;
print(isConnected);
});
});
});
return Scaffold(...)https://stackoverflow.com/questions/73251185
复制相似问题