流互联网连接整个应用

时间:2019-09-16 05:54:20

标签: flutter dart

在我的应用程序中,我想流式传输Internet连接整个应用程序的所有部分。为了流式传输此功能,我开设了此类:

enum ConnectivityStatus { Connected, Disconnected }

class ConnectivityService extends ChangeNotifier {
  StreamController<ConnectivityStatus> _connection = StreamController<ConnectivityStatus>();

  Stream<ConnectivityStatus> get stream => _connection.stream;

  ConnectivityService() {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) {
        _connection.add(isConnected ? ConnectivityStatus.Connected : ConnectivityStatus.Disconnected);
      });
    });
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      return false;
    }
    return isConnected;
  }
}

我将其定义为提供者:

List<SingleChildCloneableWidget> uiConsumableProviders = [
  ... ,
  StreamProvider<ConnectivityStatus>(
    builder: (context) => ConnectivityService().stream,
  ),
];

现在。我正在尝试使用内部视图,例如:

return Consumer<ConnectivityStatus>(
  builder: (context, isOnline, _) =>
      Scaffold(
          backgroundColor: theme.pageBackgroundColor,
          body: Container(
            child: Center(
              child: Text( isOnline != null ? isOnline.toString( ) : '', style: TextStyle( color: Colors.white ), ),
            ),
          )
      ),
);

不幸的是,我总是得到ConnectivityStatus .Disconnected,看来我的流媒体互联网连接无法正常工作

1 个答案:

答案 0 :(得分:1)

解决方案:

enum ConnectivityStatus { Connected, Disconnected }

class ConnectivityService {
  StreamController<ConnectivityStatus> _connectionStatusController = StreamController<ConnectivityStatus>();

  Stream<ConnectivityStatus>  get stream=>_connectionStatusController.stream;
  ConnectivityService() {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
      await _updateConnectionStatus().then((bool isConnected) {
        _connectionStatusController.add(isConnected ? ConnectivityStatus.Connected : ConnectivityStatus.Disconnected);
      });
    });
  }

  Future<bool> _updateConnectionStatus() async {
    bool isConnected;
    try {
      final List<InternetAddress> result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isConnected = true;
      }
    } on SocketException catch (_) {
      isConnected = false;
      return false;
    }
    return isConnected;
  }
}

提供流:

List<SingleChildCloneableWidget> uiConsumableProviders = [
  ...
  StreamProvider<ConnectivityStatus>(builder: (context) => ConnectivityService().stream),
];