Home > OS >  Flutter check for internet connection on app startup and show a snapbar
Flutter check for internet connection on app startup and show a snapbar

Time:03-22

I am making a Flutter app for android/iOS and I would like to check if the device has an internet connection on the app startup and then show a SnackBar if it doesn't have one.

Is it a good idea to send an HTTP request and if it doesn't get a response in 5 seconds it will decide that the device doesn't have an internet connection? Or is there a better way?

CodePudding user response:

The connectivity package does not guarantee the actual internet connection (could be just wifi connection without internet access).

This is what I got from documentation

Note that on Android, this does not guarantee connection to Internet. For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.

If you really need to check the connection to the www Internet the better choice would be

internet_connection_checker

CodePudding user response:

You can use connectivity_plus package in your initState to check for internet connectivity

import 'package:connectivity_plus/connectivity_plus.dart';

var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
  // I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
  // I am connected to a wifi network.
}
  • Related