Flutter: Navigate to a new screen error in MaterialApp
1 min readApr 24, 2020
The following error is displayed when build a flutter project?
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0 Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:1495:9)
#1 Navigator.of (package:flutter/src/widgets/navigator.dart:1502:6)
#2 Navigator.push (package:flutter/src/widgets/navigator.dart:1121:22)
#3 MyApp.build.<anonymous closure> (package:monee_flutter/main.dart:56:31)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
It is because there are some issues with MaterialApp context. The Navigator won’t work if you’re doing in under MaterialApp context.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: Center(child: Text("Click Me")),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => DiceScreen()),
);
},
),
),
);
}
}
In order to fix it, do not navigate to new screen under MaterialApp context.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstScreen(),
);
}
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: Center(child: Text("Click Me")),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DiceScreen()),
);
},
),
);
}
}