Hamed Rezaee
Hamed Rezaee

Reputation: 7222

access bloc from Navigator.pushNamed in flutter

I have a routing like this:

routes: {
    '/': (context) => MainPage(),
    '/othe_page': (context) => OthePage(),
},

Navigator.pushNamed(context, '/othe_page');

How can I pass bloc to OthePage widget?

Upvotes: 2

Views: 2896

Answers (2)

Mahyar Moghimi
Mahyar Moghimi

Reputation: 1

I think the first option of the current accepted answer is not the best idea. Because if you pass the bloc manually to the next screen, then you will not be able to access the bloc through your widget three with "standard" ways. Namely: BlocListener and context.read (to listen to the stream of changes) and context.read (to call exposed functions of your business logic in the bloc). This way you are just reducing the bloc to a (sort of) global variable. This is an example of working "against the framework".

The second option of using the BlocProvider is decent though. If you use a anonymous routing, though it would be a little bit easier. In that case you will call a BlocProvider.value and pass the value of your bloc/cubit to it.

Navigator.of(context).push(
  MaterialPageRoute<void>(
    builder: (_) => BlocProvider.value(
      value: yourcubitOrBloc,
    child: const otherPage(),
  ),

However if you really want to go with the named routing, you will have to define the bloc/cubits on a higher level, wehere you define your routing. That means your routes would look like this:

routes: {
'/': (context) => BlocProvider.value(value: yourCubitOrBloc child: MainPage(),
'/othe_page': (context) => BlocProvider.value(value: yourCubitOrBloc child:  OthePage(),

},

Note that you should define "yourCubitOrBloc" inside the app which should be a statefullwidget in this case. and you should also take care of disposing it by calling the cubt.close() in the dispose method of your widget.

There is a very good tutorial on this here: https://youtu.be/laqnY0NjU3M?si=IR13aES0mUjtFmHe

Upvotes: 0

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27177

1) passing bloc as a argument

You have to pass your bloc as argument in navigator as below.

Navigator.pushNamed(context, '/deletewidget',
                    arguments: bloc);

Now you have to accept that bloc in new page as below.

class _DeleteWidgetState extends State<DeleteWidget> {
var bloc;
@override
Widget build(BuildContext context) {
bloc = ModalRoute.of(context).settings.arguments;

Note: you have to create bloc variable out of build method and assign bloc variable in build method.

-when you return to last screen then you will not able to access bloc anymore.

2) you can use bloc provider in parent widget so that you can access your bloc in new screen also.

for more detail check out Flutter_bloc package.

Upvotes: 4

Related Questions