0

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

James Piner
  • 199
  • 1
  • 4
  • 17

1 Answers1

3

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

EdYuTo
  • 6,374
  • 3
  • 11
  • 22