Harshvardhan R
Harshvardhan R

Reputation: 477

How to make network calls when flutter app changes from offline to online?

I am working on an flutter app that stores data in the database in the form of objects when it is offline. When the user is back online the app must make all the post requests .Is it possible to find out when the user is back online and can i do it even if the user is on another app or locked out .

Upvotes: 1

Views: 434

Answers (1)

Tom Rivoire
Tom Rivoire

Reputation: 651

You can use the package connectivity
And create a stream to listen to connectivity changes.

Define a stream :

StreamSubscription<ConnectivityResult> networkSubscription;

In the initState() method add :

networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // This will be called every time a connectivity change happens
    try {
        final result = await InternetAddress.lookup('google.com');
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            print('Connected to internet');
            // Connectivity changed from disconnected to connected
        }
    } on SocketException catch (_) {
        print('Not connected to internet');
        // Connectivity changed from connected to disconnected 
    }
});

Don't forgot to dispose the stream :

@override
void dispose() {
    networkSubscription.cancel();
    super.dispose();
}

I don't know how to do this when the app is closed or on background.

Upvotes: 2

Related Questions