简体   繁体   English

Flutter 中的连续流连接

[英]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.还有其他类似于我的问题,但我对如何从连接<\/a>插件包实现连续连接流有点迷茫。

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() .您可以使用AppStateProvider和应用程序级showDialog() Keep in mind that, there is an onConnectivityChanged property in this package.请记住,此包中有一个onConnectivityChanged属性。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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