我正在制作一个 Flutter 应用程序,我想在执行其他操作之前检查用户是否启用了 wifi。
if (wifiEnabled) {
//Do stuff
}
else {
//Tell the user to turn on wifi
}
我有一个代码片段可以让我检查用户是否有来自这篇文章的互联网连接。 Check whether there is an Internet connection available on Flutter app
void _checkWifi() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
_wifiEnabled = true;
}
} on SocketException catch (_) {
print('not connected');
_wifiEnabled = false;
}
}
我遇到的问题是因为 checkWifi 函数是异步的。如果用户从没有 wifi 变为有 wifi,则在检查 if(wifiEnabled) 代码时 bool 值不会更新,因此根据逻辑 wifiEnabled 将为 false,尽管用户有 wifi。
如果用户再次尝试,他们将拥有 wifi,因为 wifiEnabled 将更新为 true。我试过使用 Timer 和 Future.delayed 但到目前为止我还没有解决我的问题。
一般来说,处理问题或异步调用的任何建议都会非常有帮助。谢谢
最佳答案
希望下面的代码能帮助您理解。
class YourWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
showWifiAlert();
return ...
}
void showWifiAlert() async {
var wifiEnabled = await getWifiStatus();
if (wifiEnabled) {
//Do stuff
}
else {
//Ask user to enable internet
}
}
Future<bool> getWifiStatus() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
return true;
}
} on SocketException catch (_) {
print('not connected');
return false;
}
}
}
关于asynchronous - 在 Flutter 应用程序中处理异步 wifi 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574659/