State or event not getting changed in flutter bloc

Viewed 4244

I have defined one abstract stateless widget following way


abstract class BaseStatelessWidget<T extends Bloc> extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    if (shouldHideStatusBar) {
      SystemChrome.setEnabledSystemUIOverlays([]);
    }

    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) {
            BaseBloc baseBloc = getIt<BaseBloc>();
            baseBloc.add(BaseEvent.networkListeningInitiated());
            return baseBloc;
          },
        ),
        BlocProvider(
          create: (context) => getImplementedBloc(context),
        ),
      ],
      child: BlocListener<BaseBloc, BaseState>(
        listener: _handleState,
        child: buildScreen(context),
      ),
    );
  }

  bool get shouldHideStatusBar => false;

  _handleState(BuildContext context, BaseState state) {
    // here different state will be managed
  }


  Widget buildScreen(BuildContext context);

  T getImplementedBloc(BuildContext context);
}



Another stateless widget SigninPage extending it following way

class SigninPage extends BaseStatelessWidget<SigninBloc> {
  @override
  Widget buildScreen(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: SigninForm(),
      ),
      resizeToAvoidBottomInset: true,
    );
  }

  @override
  bool get shouldHideStatusBar => true;

  @override
  SigninBloc getImplementedBloc(BuildContext context) {
    return getIt<SigninBloc>();
  }
}

For sake of this question i removed redundant codes from SingInForm class here is the code :

class SigninForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PrimaryButton(
      btnText: getString(context, StringKeys.signin),
      onButtonClick: () => onSignin(context),
    );
  }

  onSignin(BuildContext context) {
    context.bloc<BaseBloc>().add(BaseEvent.changeLoaderStatus(visible: true)); => this is not working I tried to check if it is null. this is not null
    context.bloc<SigninBloc>().add(SigninEvent.loginWithEmailPassword()); => this is working fine
  }
}

This is my BaseBloc class defined. Neither mapEventToState() method nor onTransition() method getting called.

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';
import 'package:refyne_app/domain/core/i_network_aware_facade.dart';
import 'package:refyne_app/domain/core/logger.dart';
import 'package:refyne_app/infrastructure/core/api_service/connectivity_status.dart';

part 'base_event.dart';
part 'base_state.dart';
part 'base_bloc.freezed.dart';

@injectable
class BaseBloc extends Bloc<BaseEvent, BaseState> {
  INetworkAwareFacade _networkHandlerFacade;

  BaseBloc(this._networkHandlerFacade)
      : super(BaseState.initial(
          isLoaderVisible: false,
        ));

  @override
  Stream<BaseState> mapEventToState(
    BaseEvent event,
  ) async* {
    yield* event.map(
      networkListeningInitiated: (_) => _handleNetworkChange(),  <== This one is causing the issue, if i remove this method. It works fine.
      networkListeningStopped: (_) async* {},
      changeLoaderStatus: (ChangeLoaderStatus value) async* {
        logger.d('from bloc loader called with $value');
        yield state.copyWith(isLoaderVisible: value.visible);
      },
    );
  }

  Stream<BaseState> _handleNetworkChange() async* {
    await for (ConnectivityResult result
        in _networkHandlerFacade.onConnectionChange()) { <== onConnectionChange will give you a stream
      if (result == ConnectivityResult.none) {
        yield state.copyWith(
            connectionStatus: ConnectionStatus(
          type: ConnectionType.NONE,
          isworking: false,
        ));
      } else {
        bool isworking = await _networkHandlerFacade.checkConnection();
        ConnectionType type = result == ConnectivityResult.mobile
            ? ConnectionType.MOBILE
            : ConnectionType.WIFI;

        yield state.copyWith(
          connectionStatus: ConnectionStatus(type: type, isworking: isworking),
        );
      }
    }
  }

  @override
  void onError(Object error, StackTrace stackTrace) {
    if (error is Exception) {
      _handleException(error);
    } else {
      super.onError(error, stackTrace);
      // TODO:: handle this exception scenario
    }
  }

  _handleException(Exception e) {
    print(e);
  }

  @override
  void onTransition(Transition<BaseEvent, BaseState> transition) {
    logger.d('from base bloc ${transition.event}');
    logger.d('from base bloc ${transition.currentState}');
    logger.d('from base bloc ${transition.nextState}');
    super.onTransition(transition);
  }
}


i am trying to access base bloc defined in BaseStatelessWidget class. My defined child bloc is working fine and it is also sending events as well. My problem is i am not able to change the state of parent bloc. Can someone tell me what i am doing wrong? any help will be appreciated. Thanks...

1 Answers

After struggling for the whole one day, Now I understand why it was happening. I was handling stream directly inside mapEventToState method. When i moved stream handling from mapEventToState to constructor, then it is working fine. Hope it will help someone...

See this example for more info.

Flutter Bloc with Stream

Related