Flutter:当连接状态改变时,是否可以在 main.dart 中为所有屏幕实现一次快餐栏

Flutter : is it possible to implement a snackbar one time in main.dart for example for all screen when the connectivity status changed

enum ConnectivityStatus{
  Wifi,
  Cellular,
  Offline
}
import 'dart:async';

import 'package:Zabatnee/activities_app/enum/connectivity_status.dart';
import 'package:connectivity/connectivity.dart';

class ConnectivityService{

StreamController<ConnectivityStatus> connectionStatusController = StreamController<ConnectivityStatus>();

ConnectivityService(){
  Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { 
    var connectionStatus = _getStatusFromResult(result);
    connectionStatusController.add(connectionStatus);
  });
}
  ConnectivityStatus _getStatusFromResult(ConnectivityResult result) {
    switch (result) {
      case ConnectivityResult.mobile:
        return ConnectivityStatus.Cellular;
      case ConnectivityResult.wifi:
        return ConnectivityStatus.Wifi;
      case ConnectivityResult.none:
        return ConnectivityStatus.Offline;
      default:
        return ConnectivityStatus.Offline;
    }
  }
}

您可以检查一次连接状态,这将适用于您的所有应用。

您只需创建包装器 class 并订阅 Connectivity 流并在该包装器中应用逻辑 class。

您的整个小部件将被此小部件包裹。

MaterialApp(
  ..
  home: ConnectivityWrapper(
    childWidget: YourWidget(), // replace this with your own home widget
  ),
);

包装器小部件将如下所示:

class ConnectivityWrapper extends StatefulWidget {
  
  ConnectivityWrapper(this.childWidget);
  
  final Widget childWidget;

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

class _ConnectivityWrapperState extends State<ConnectivityWrapper> {

  StreamSubscription<ConnectivityStatus> subscription;

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

    subscription = connectionStatusController.stream.listen((status) 
      {
        if(status == ConnectivityStatus.Offline) {
          // Your logic here (Toast message or something else)
        }
      }, 
      onDone() {
        // Your logic here
      }, 
      onError: () {
        // Your logic here
      });
  }

  @override
  Widget build(BuildContext context) {
    return widget.childWidget;
  }

  @override
  void dispose() {
    // unsubscribe to the stream
    subscription.cancel();
    super.dispose();
  }
}