I am learning flutter. Below is my basic code. I get an error saying that my button in appBar doesnt have acces to the Navigator.
import 'package:flutter/material.dart';
import 'package:new_app/pages/first_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.arrow_forward_ios,
color: Colors.black,
),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => FirstPage()));},
)
]),
body: Center(
child: Text('Sample Text'),
),
),
);
}
}
I dont get it as it seems directly under Scaffold and MaterialApp so it should? Can someone explain this to me in plain terms?
Think of the widgets in Flutter as a tree, with the context pointing to whichever node is being built with the build function. In your case, you have
MyApp <------ context
--> MaterialApp
(--> Navigator built within MaterialApp)
--> Scaffold
--> App Bar
--> IconButton
--> Center
-->Text
So when you're using the context to find the Navigator, you're using a context for the MyApp which isn't under the navigator.
You can either make a new Stateless or Stateful Widget subclass to contain your AppBar + IconButton, as the build function within those will point at that level instead, or you can use a Builder and define the builder
callback (which has a context pointing at the Builder) to return the AppBar + IconButton.
Similar question: here