简体   繁体   中英

Continuous stream connectivity in Flutter

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<\/a> 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,
    );
  }
}

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 .

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM