简体   繁体   English

Flutter 中的连接页面

[英]Connectivity page in Flutter

I tried using the top rated answer: Check whether there is an Internet connection available on Flutter app to check if I had an internet connection, but I need to create a page that displays a text saying no signal if the catch returns an error, but I don't know how to do this in flutter.我尝试使用评分最高的答案: 检查 Flutter 应用程序上是否有可用的 Internet 连接以检查我是否有 Internet 连接,但我需要创建一个页面,显示如果 catch 返回错误时没有信号的文本,但是我不知道如何在 flutter 中执行此操作。 Then if there is no error, the normal main menu page is returned.然后如果没有错误,则返回正常的主菜单页面。 Thanks谢谢

Here is a quick solution, but probably not the best one:这是一个快速的解决方案,但可能不是最好的:

With the link you provided we can create a function like this:使用您提供的链接,我们可以像这样创建 function:

Future<bool> _checkIfConnected() 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;
  }
}

This will check if you are connected and the return a future with a bool value that tells if your connection was successful or not.这将检查您是否已连接,并返回一个带有 bool 值的未来,该值表明您的连接是否成功。

Then on your widget, you could use a future builder like this:然后在您的小部件上,您可以使用这样的未来构建器:

FutureBuilder(
    future: _checkIfConnected(),
    builder: (context, isConnected) =>
        isConnected.connectionState == ConnectionState.done
            ? isConnected.data
                ? // your main menu here //
                : Center(
                    child: Text('no signal'),
                  )
            : CircularProgressIndicator(),
  )

Since the connection check returns a future, you must use a future builder here.由于连接检查返回一个未来,因此您必须在此处使用未来构建器。 It simply returns a widget depending on the state of your future.它只是根据您未来的 state 返回一个小部件。 More about future builder here更多关于未来建设者的信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM