flutter BlocProvider Navigation

268

In order to pass an already created bloc to consequent screen you can use the BlocProvider.value your code would be like this after the change :

Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) {
      return BlocProvider.value(
        value: BlocProvider.of<BlocA>(context),
        child: PageB(),
      );
    },
  ),
);

PageB should be able to retrieve blocA now.

Share:
268
reza
Author by

reza

Flutter Developer

Updated on January 01, 2023

Comments

  • reza
    reza over 1 year

    suppose that we navigate to "PageA" using the following code:

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          return BlocProvider(
            create: (context) => BlocA(),
            child: PageA(),
          );
        },
      ),
    );
    

    when "PageA" navigates to "PageB". how can I access "BLocA"? I have tried following code to navigate from "PageA" to "PageB" but it crashes.

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          return BlocProvider(
            create: (context) => contxt.read<BlocA>(),
            child: PageB(),
          );
        },
      ),
    );
    
  • reza
    reza over 2 years
    BlocProvider has not "value" named property
  • Abdelkrim Bournane
    Abdelkrim Bournane over 2 years
    Sorry, my bad, I have corrected the code.