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?


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;
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.

Answered By – Viren V Varasadiya

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

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