Unhandled Exception: Navigator operation requested with a context that does not include a Navigator

Published December 29, 2022

When we run flutter applications some times we may get this issue, This issue come because when we do Navigator.of(context), it will start from the widget associated to the context used. And then go upward in the widget tree until it either find a Navigator or there’s no more widget.

So, it throws an Error

Navigator operation requested with a context that does not include a Navigator.

So, how do we fix it ?

First, let’s reproduce this error :

 

import 'package:flutter/material.dart';

 

void main() => runApp(MyApp());

 

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Center(

child: RaisedButton(

child: Text("Foo"),

onPressed: () => Navigator.pushNamed(context, "/"),

),

),

);

}

}

This example creates a button that attempts to go to ‘/’ on click but will instead throw an exception.

observe that 

onPressed: () => Navigator.pushNamed(context, "/"),

we used context passed by to build of MyApp. The issue is, MyApp is actually a parent of MaterialApp. As it’s the widget who instantiate MaterialApp! Therefore MyApp’s BuildContext doesn’t have a MaterialApp as parent!

To resolve  this issue, we need to use a different context.

In this case, the easiest way to resolve the issue  is to introduce a new widget as child of MaterialApp. And then use that widget’s context to do the Navigator call.

We have different ways to achieve this. We can extract home into a custom class :

 

 

import 'package:flutter/material.dart';

 

void main() => runApp(MyApp());

 

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: MyHome()

);

}

}

 

class MyHome extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Center(

child: ElevatedButton(

child: Text("Foo"),

onPressed: () => Navigator.pushNamed(context, "/"),

),

);

}

}

 

Or you can use Builder :

 

import 'package:flutter/material.dart';

 

void main() => runApp(MyApp());

 

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Builder(

builder: (context) => Center(

child: ElevatedButton(

child: Text("Foo"),

onPressed: () => Navigator.pushNamed(context, "/"),

),

),

),

);

}

}

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

179 Views