Continuous stream connectivity in Flutter

1k views Asked by At

I've already succeeded at checking the connection on this Main Menu page, but I need this to continuously be checked at every other page in my app. Is there another way in which I could continuously check the connection without having to re-write my code everywhere? There are other questions similar to mine, but I'm a bit lost on how to implement a continuous connectivity stream from the connectivity plugin package.

class MainMenu extends StatefulWidget {

  MainMenu({this.latCoordinates, this.longCoordinates, this.postcode});

   final double latCoordinates;
   final double longCoordinates;
   final String postcode;

  @override
  _MainMenuState createState() => _MainMenuState();
}


class _MainMenuState extends State<MainMenu> with SingleTickerProviderStateMixin {

  bool isConnected = false;
  bool showSpinner = false;

  void connect() async {
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        setState(() {
          isConnected = true;
          showSpinner = false;
        });
      }
    } on SocketException catch (_) {
      setState(() {
        isConnected = false;
        Timer(Duration(seconds: 2), (){
          setState(() {
            showSpinner = false;
          });
        });
        // showSpinner = false;
      });
    }
  }


  @override
  void initState() {
    connect();
    super.initState();
  }


  @override
  Widget build(BuildContext context) {

    return isConnected ? Scaffold(

      backgroundColor: Colors.white,
    ) :

    ModalProgressHUD(
      inAsyncCall: showSpinner,
      child: Scaffold(
        backgroundColor: Colors.green,
    );
  }
}
2

There are 2 answers

0
Akif On BEST ANSWER

You can use an AppStateProvider and an app-level showDialog(). Keep in mind that, there is an onConnectivityChanged property in this package. You don't need to check connectivity on every page. It does itself. You just listen to it.

For more information.

0
Eray Hamurlu On

Use like this fixed for me.

@override
void initState() {
final Stream<List<PurchaseDetails>> purchaseUpdated =
    _inAppPurchase.purchaseStream;
_subscription = purchaseUpdated.listen((purchaseDetailsList) {
  _listenToPurchaseUpdated(purchaseDetailsList);
}, onDone: () {
  _subscription.cancel();
}, onError: (error) {
  // handle error here.
});
 initStoreInfo();
 super.initState();
}