Flutter 如何从aync/WAIT函数返回布尔值并将其传递给其他页面中的其他变量

Flutter 如何从aync/WAIT函数返回布尔值并将其传递给其他页面中的其他变量,flutter,dart,async-await,Flutter,Dart,Async Await,我想检查设备是否连接到internet,我使用了完成此工作的类,并向我返回bool值,我从该类使用到其他页面,并将返回值传递到bool变量,但得到了这样一个错误,即Future不是类型转换中bool类型的子类型 import 'dart:io'; class CheckConnection{ static Future<bool> checkConnection() async { try { final result = await InternetAd

我想检查设备是否连接到internet,我使用了完成此工作的类,并向我返回bool值,我从该类使用到其他页面,并将返回值传递到bool变量,但得到了这样一个错误,即
Future
不是类型转换中bool类型的子类型

import 'dart:io';

class CheckConnection{
  static Future<bool>  checkConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
         return (await checkConnection()) == true;
      }
    } on SocketException catch (_) {
      print('not connected');
    }
  }
}     
导入'dart:io';
类检查连接{
静态未来checkConnection()异步{
试一试{
最终结果=等待InternetAddress.lookup('google.com');
if(result.isNotEmpty&&result[0].rawAddress.isNotEmpty){
return(wait checkConnection())==true;
}
}关于SocketException捕获(41;{
打印(“未连接”);
}
}
}     

我不明白为什么要在内部再次调用checkConnection(递归效果)。您确定不想这样做吗:

class CheckConnection {

  static Future<bool>  checkConnection() async {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      return true;
    }
/* try catch also can be applied! */ 

    return false;
  }
}
类检查连接{
静态未来checkConnection()异步{
最终结果=等待InternetAddress.lookup('google.com');
if(result.isNotEmpty&&result[0].rawAddress.isNotEmpty){
返回true;
}
/*也可以应用try catch!*/
返回false;
}
}

我不明白为什么要在内部再次调用checkConnection(递归效果)。您确定不想这样做吗:

class CheckConnection {

  static Future<bool>  checkConnection() async {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      return true;
    }
/* try catch also can be applied! */ 

    return false;
  }
}
类检查连接{
静态未来checkConnection()异步{
最终结果=等待InternetAddress.lookup('google.com');
if(result.isNotEmpty&&result[0].rawAddress.isNotEmpty){
返回true;
}
/*也可以应用try catch!*/
返回false;
}
}

在需要检查的地方,必须执行以下操作:

CheckConnection.checkConnection().then((bool result){
  /* check result here  */
})
或者您可以在
async
函数中执行此操作,如
checkConnection

void _myFunction() async {
  bool result = await CheckConnection.checkConnection();
  /* check result here  */
}

在需要检查的地方,您必须执行以下操作:

CheckConnection.checkConnection().then((bool result){
  /* check result here  */
})
或者您可以在
async
函数中执行此操作,如
checkConnection

void _myFunction() async {
  bool result = await CheckConnection.checkConnection();
  /* check result here  */
}
把这个还给我

return await checkConnection();
把这个还给我

return await checkConnection();

你能把你的密码寄出去吗?所以我们可以帮你。你能发布你的代码吗?所以我们可以帮忙。