简体   繁体   中英

Why internet connection status is not listened in Cubit Constructor when running code in flutter web

I use from connectivity_plus for listening to internet connection and handling status with flutter cubit.

when i run code on flutter web, status stay on NetLoading() untill once, i turn off(turn on) internet, but with run on android device not exist problem.

my Cubit

class NetConnectionCubit extends Cubit<NetConnectionState> {
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription _connectivityStreamSubscription;

  NetConnectionCubit() : super(NetLoading()) {
    _connectivityStreamSubscription =
        _connectivity.onConnectivityChanged.listen(
      (result) {
        if (result == ConnectivityResult.none) {
          emitNetDisConnected();
        } else {
          emitNetConnected();
        }
      },
    );
  }

  void emitNetConnected() => emit(NetConnected());

  void emitNetDisConnected() => emit(NetDisconnected());

  /// close(cancel) _connectivityStreamSubscription
  /// but we know in all of app lifecycle this stream bust be live
  /// so this function never be run
  @override
  Future<void> close() {
    _connectivityStreamSubscription.cancel();
    return super.close();
  }
}

and BlocBuilder

MultiBlocProvider(
      providers: [
        BlocProvider<NetConnectionCubit>(create: (_) => NetConnectionCubit()),
      ],
      child: BlocBuilder<NetConnectionCubit, NetConnectionState>(
        builder: (context, state) {
          return child()
....

Use checkConnectivity to check current status. Changes are only exposed to the stream.

final connectivityResult = await Connectivity().checkConnectivity();

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