Flutter 中的连续流连接

Continuous stream connectivity in Flutter

我已经成功地检查了这个主菜单页面上的连接,但我需要在我的应用程序的每个其他页面上持续检查它。有没有另一种方法可以让我连续检查连接而不必在所有地方重写我的代码?还有其他类似我的问题,但我对如何从 connectivity 插件包实现连续连接流有点迷茫。

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

您可以使用 AppStateProvider 和 app-level showDialog()。请记住,此包中有一个 onConnectivityChanged 属性。您不需要检查每个页面上的连接性。它自己做。你随便听听。

更多information.

像我这样固定使用。

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