How to provide bloc to replaced widget through pushReplacement?


I have a parent stless widget like so,

class LoginScreen extends StatelessWidget {
   final AuthRepository authRepository = AuthRepository(AuthApiClient());
   Widget build(BuildContext context) {
      return BlocProvider(
          create: (BuildContext context) {
            return LoginBloc(Idle(), authRepository);
          child: LoginWithEmailIdScreen(),

I’m able to access the bloc in LoginWithEmailIdScreen just fine, but when I replaceLoginWithEmailIdScreen with another screen (LoginWithMobileNumberScreen) as so, the bloc instance seems to be null.
Inside LoginWithEmailIdScreen :

      builder: (_) => BlocProvider.value(
         value: BlocProvider.of<LoginBloc>(context),
         child: LoginWithMobileNumberScreen(),

Thought it was the wrong context being used, so replaced it with _ but still the same issue.

How to provide the bloc instance?

Any help is appreciated as I’m very new to flutter. Thanks.


I couldn’t find a good way to provide bloc through pushReplacement without using routes.

Had to refactor the whole project and implement routes to used named alternatives as so :

                  (Route<dynamic> route) => false);

and pass the bloc and manage in onGenerateRoute.

Answered By – CyberShark

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *