Flutter Block : Unable to access updated state field in second screen in multi page state form

Viewed 24

I need help.

I am creating a multi page form which is divided into 2 screens.

  1. First Screen
  2. Second Screen

Both screen share same bloc which is FormBloc, and same state which is FormState. When we click submit button in first screen, it update the state variables using state.copyWith() method and then it take us to 2nd screen. I am using Navigator.pushNamed(context, '/screen2'); to move to second screen.

Bloc is provided to second screen from the AppRoute class:

static final _formBloc = FormBloc();
  
Following code is called during Navigation:
  // Route to second screen
  static BlocProvider<FormBloc> secondScreenRoute() {
    return BlocProvider.value(value: _formBloc, child: const SecondScreen());
  }

But In the second screen all the fields which was updated using state.copyWith() method gets restored to their initial state.

For Example: In first Screen there is input formtextfield for user name. When user enters his name, I update state using state.copywithMethod() Suppose user enter name "John" then

emit(state.copyWith(
          name: John,
          status: Formz.validate([state.name, name]),
        ));

And When I am accessing this in second screen using state.name then I am getting empty string "".

I fail to understand why this is happening. I am not creating new bloc instance and I am passing already created bloc instance to second screen but then also all the properties which was updated using state.copyWith() method gets restored to their initial value on second screen.

Could you please help?

1 Answers

You can try better instead of using BlocProvider.value, create the Bloc globally in your MaterialApp as follows :

return 
    BlocProvider<FormBloc>( // like this
       create: (context) => FormBloc(),
       child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Demo',
          initialRoute: PageNames.login,
          onGenerateRoute: RouteGenerator.generateRoute,
       ),
    ),
);

This will allow to have it already created when you start your application, and thus all the Blocs that you occupy later will have the value in the state.

Now just try to do a normal navigation, remove the other BlocProvider you have created as well as the .value.

Related