简体   繁体   中英

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. 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:

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.

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. More about future builder here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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