text stringlengths 1 474 |
|---|
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()), |
); |
}, |
), |
), |
); |
} |
} |
class SecondRoute extends StatelessWidget { |
const SecondRoute({super.key}); |
@override |
Widget build(BuildContext context) { |
return Scaffold( |
appBar: AppBar( |
title: const Text('Second Route'), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.