How to Navigate one page to another in Flutter using Navigator?
The Navigator widget in Flutter provides a way to manage a stack of routes.
You can use the Navigator to
- named routes,
- push
- And pop routes,
Where each route is an independent widget. You can use the Navigator to transition between pages by providing the widget you want to display on the page, and we can use the Navigator to specify the route you want to use to transition between pages.
Using Navigator in Flutter is simple. Here's an example of how to use Navigator to navigate between two screens:
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go to Second Screen'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go back to First Screen'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
When the button is pressed, the Navigator.push method is called to push a new route (SecondScreen) onto the stack.
When the back button is pressed, the Navigator.pop method is called to remove the current route (SecondScreen) from the stack and return to the previous route (FirstScreen).
When the button is pressed, the Navigator.push method is called to push a new route (SecondScreen) onto the stack. When the back button is pressed, the Navigator.pop method is called to remove the current route (SecondScreen) from the stack and return to the previous route (FirstScreen).
Named Route:
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
)
onPressed: () {
Navigator.pushNamed(context, '/second');
},
onPressed: () {
Navigator.pop(context);
},
Simple Example for NamedRoute:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
},
);
}
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go to Second Screen'),
onPressed: () {
Navigator.pushNamed(context, '/second');
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: RaisedButton(
child: Text('Go back to First Screen'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
Comments
Post a Comment