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

Time:07-27

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()
....

CodePudding user response:

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

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