How to verify if user has network access and show a pop-up alert when there isn't

My name is Pablo and I am currently building a Flutter app. So, my app gets some images and audios from Firebase Storage, and obviously, without the internet connection, the app doesn’t display the images and doesn’t play the audios.
I want the app to pop-up an alert to the user when there is no WIFI nor Data; how can I do that?

Thanks 🙂

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can simply use a function to check if you have network connection, by pinging Google servers:

/system/bin/ping -c 1 8.8.8.8

In Android, this function looks like this:

public boolean isNetworkAvailable() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = process.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}

In Firestore, offline persistence is enabled by default. So you can check if the user reads data from the cache or from Firebase servers. A more elegant way would be to use isFromCache() function. This is the code for Android:

yourDocRef.addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
        Log.d("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});

Solution 2

You can use the connectivity package https://pub.dartlang.org/packages/connectivity
Here is a simple tutorial with the dart file attached https://medium.com/@aseemwangoo/internet-connectivity-in-flutter-a6b6aedf2964

Possible duplicate – Check whether there is an Internet connection available on Flutter app

Solution 3

For showing alert part, you can use RFlutter Alert library. It is easily customizable and easy-to-use alert/popup dialog library for Flutter.

Example code:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

*I’m one of developer of RFlutter Alert.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply