text
stringlengths
1
372
class FirstRoute extends StatelessWidget {
const FirstRoute({super.key});
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('First route'),
),
body: center(
child: ElevatedButton(
child: const Text('Open route'),
onPressed: () {
// navigate to second route when tapped.
},
),
),
);
}
}
class SecondRoute extends StatelessWidget {
const SecondRoute({super.key});
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Second route'),
),
body: center(
child: ElevatedButton(
onPressed: () {
// navigate back to first route when tapped.
},
child: const Text('Go back!'),
),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
2. navigate to the second route using navigator.push()
to switch to a new route, use the navigator.push()
method. the push() method adds a route to the stack of routes managed by
the navigator. where does the route come from?
you can create your own, or use a MaterialPageRoute,
which is useful because it transitions to the
new route using a platform-specific animation.
in the build() method of the FirstRoute widget,
update the onPressed() callback:
<code_start>
// within the `firstroute` widget
onPressed: () {
navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
}
<code_end>
<topic_end>
<topic_start>
3. return to the first route using navigator.pop()
how do you close the second route and return to the first?
by using the navigator.pop() method.
the pop() method removes the current route from the stack of
routes managed by the navigator.
to implement a return to the original route, update the onPressed()
callback in the SecondRoute widget:
<code_start>
// within the SecondRoute widget
onPressed: () {
navigator.pop(context);
}
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
title: 'navigation basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatelessWidget {
const FirstRoute({super.key});
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('First route'),
),
body: center(
child: ElevatedButton(
child: const Text('Open route'),
onPressed: () {
navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),