Home > Blockchain >  When opening the application, immediately show the SnackBar if there is no Internet connection
When opening the application, immediately show the SnackBar if there is no Internet connection

Time:06-21

I am using connectivity_plus package to test internet connection. If there is no connection, I show the SnackBar. But for me it works when I go into the application and turn off the connection. But how can I make it so that if I immediately entered the application without the Internet and automatically, without any action, it was displayed that there was no Internet?

bloc

class ConnectedBloc extends Bloc<ConnectedEvent, ConnectedState> {
  StreamSubscription? subscription;

  ConnectedBloc() : super(ConnectedInitial()) {
    on<OnConnectedEvent>((event, emit) => emit(ConnectedSucess()));
    on<OnNotConnectedEvent>((event, emit) => emit(ConnectedFailure()));

    Connectivity()
            .onConnectivityChanged
            .listen((ConnectivityResult result) {
          if (result == ConnectivityResult.wifi ||
              result == ConnectivityResult.mobile) {
            add(OnConnectedEvent());
          } else {
            add(OnNotConnectedEvent());
          }
        });

home

home: BlocConsumer<ConnectedBloc, ConnectedState>(
          listener: ((context, state) {
            if (state is ConnectedSucess) {
              const SizedBox();
            } else if (state is ConnectedFailure) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  duration: const Duration(seconds: 3),
                  backgroundColor: Colors.transparent,
                  elevation: 0,
                  content: SystemMessagesSnackBar(
                    message: 'No internet access. Check your connection',
                    textButton: 'Refresh',
                    onPressed: () =>
                        ScaffoldMessenger.of(context).hideCurrentSnackBar(),
                    icon: SvgPicture.asset(constants.Assets.no_connection),
                  ),
                ),
              );
            }
          }),

CodePudding user response:

Code only listen changes, get current status like this:

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