nike
nike

Reputation: 745

Continuously check internet disconnection on Flutter app

I'm creating a mobile application on Flutter and I'm calling REST API's created on Node.js in order to connect and query my oracle DB all the time.

I've use so far the connectivity 0.3.2 in order to check the network connectivity before the async call or login operation. Like the example below :

    checkConnectivity(context) async{

  String connectionStatus;
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  final Connectivity _connectivity = new Connectivity();
  try {
    connectionStatus = (await _connectivity.checkConnectivity()).toString();
    _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      connectionStatus = result.toString();
      //   print(connectionStatus);
    });
  } on PlatformException catch (e) {
    print(e.toString());
    connectionStatus = 'Failed to get connectivity.';
  }
  if(connectionStatus == "ConnectivityResult.none"){
    components.alertPopup(context, "No Internet Connection available" , "Please check your internet connection and try again");}

}

I want to ask if there is any possible way to continuously check internet disconnection in every moment that the user is using the application (even if he is just reading data, without making an API call at all).

In order to notify the user that he is offline with a SnackBar for example.

Upvotes: 9

Views: 11901

Answers (3)

Ayoub BOUMZEBRA
Ayoub BOUMZEBRA

Reputation: 5033

your pubspec.yaml, add the following lines as :

flutter_offline: "^0.3.0"

Import

import 'package:flutter_offline/flutter_offline.dart';

Exemple :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            title: Text("Connection status"),
          ),
          body: Builder(
            builder: (BuildContext context) {
              return OfflineBuilder(
                connectivityBuilder: (BuildContext context,
                    ConnectivityResult connectivity, Widget child) {
                  final bool connected =
                      connectivity != ConnectivityResult.none;
                  return Stack(
                    fit: StackFit.expand,
                    children: [
                      child,
                      Positioned(
                        left: 0.0,
                        right: 0.0,
                        height: 32.0,
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          color:
                              connected ? Colors.green : Colors.red,
                          child: connected
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      "YOU ARE OFFLINE",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ],
                                )
                              : Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      "YOU ARE OFFLINE",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                    SizedBox(
                                      width: 8.0,
                                    ),
                                    SizedBox(
                                      width: 12.0,
                                      height: 12.0,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2.0,
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                                Colors.white),
                                      ),
                                    ),
                                  ],
                                ),
                        ),
                      ),
                    ],
                  );
                },
                child: Center(
                  child: Text("ONLINE Or OFFLINE"),
                ),
              );
            },
          )),
    );
  }
}

Upvotes: 0

nike
nike

Reputation: 745

I've just implement this packages https://pub.dartlang.org/packages/flutter_offline that deal with this issue really straightforward.

Firs tstep is import the package import 'package:flutter_offline/flutter_offline.dart';

that you included in you project and start using the library as the following example shows:

After that you include the OfflineBuilder on Widget build(BuildContext context) { and it will read all all stream changes from ConnectivityResult even if the user is not interacting with the app at all (or is only reading data) and connectivity status change.

    @override
  Widget build(BuildContext context) {
    return OfflineBuilder(

        debounceDuration: Duration.zero,
        connectivityBuilder: (
            BuildContext context,
            ConnectivityResult connectivity,
            Widget child,
            ) {
          if (connectivity == ConnectivityResult.none) {

            return Scaffold(
              appBar: AppBar(
                title: const Text('Home'),
              ),
              body: Center(child: Text('Please check your internet connection!')),
            );
          }
          return child;
        },


        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: AppBar(
              title: Text("Home")
          ),
          body: new Column(
            children: <Widget>[
              new Container(
                decoration: new BoxDecoration(color: Theme.of(context).cardColor),
                child: _buildTxtSearchBox(),
              ),
              new Divider(height: 10.0),
              new FloatingActionButton.extended(
                icon: Icon(Icons.camera_alt),
                label: Text("Barcode"),
                onPressed: _scanQR,
              ),
              new Container(
                // padding: EdgeInsets.only(left: 24.0, right: 24.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Column(
                      children: [
                        Icon(Icons.hotel, color: Colors.blueGrey[600]),
                      ],
                    ),
                    Column(
                      children: [
                        Icon(Icons.hotel, color: Colors.blue[400]),
                      ],
                    ),
                  ],
                ),

                alignment: Alignment(0.0, 0.0),
              ),
            ],
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          drawer: MenuDrawer(),
        )
    );
  }

Upvotes: 3

Alex Meuer
Alex Meuer

Reputation: 1789

You've already written the code to do what you want. You could easily wrap it in a page State or an InheritedWidget or some other managerial class.

final Connectivity _connectivity;
final StreamSubscription<ConnectivityResult> _subscription;

ConstructorForWhateverClassThisIs() {
    _connectivity = new Connectivity();
    _subscription = _connectivity.onConnectivityChanged.listen(onConnectivityChange);
}

void onConnectivityChange(ConnectivityResult result) {
    // TODO: Show snackbar, etc if no connectivity
}

void dispose() {
    // Always remember to cancel your subscriptions when you're done.
    subscription.cancel();
}

According to the documentation, the onConnectivityChanged will be updated with the new result whenever it changes, meaning you can just listen for changes without ever having to manually query it.

Documentation excerpt:

You can also listen for network state changes by subscribing to the stream exposed by connectivity plugin

Upvotes: 6

Related Questions