Flutter supports navigation in a similar way to web development.
Register Routes
First, let's see the main application.
// lib/main.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: '/',
routes: {
'/': (context) => const FirstPage(),
'/second': (context) => const SecondPage()
},
);
}
}
Set the default route to initialRoute property and register routes to the routes property.
Main Page
Let's look at the code first again.
// lib/main.dart
class FirstPage extends StatefulWidget {
const FirstPage({Key? key}) : super(key: key);
@override
State<FirstPage> createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('First Page')),
body: Center(
child: Column(
children: <Widget>[
const Text('First Page'),
ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/second');
},
child: const Text('Second Page'),
),
],
mainAxisAlignment: MainAxisAlignment.center,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed('/second');
},
child: const Icon(Icons.arrow_forward_ios),
),
);
}
}
We can navigate the pages via Navigator.of(context).pushNamed() method.
Sub Pages
Now, it is the remaining parts of the full code.
// lib/main.dart
class SecondPage extends StatelessWidget {
const SecondPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Second Page')),
body: Center(
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/');
},
child: const Text('First Page'),
),
const Text('Second Page'),
],
mainAxisAlignment: MainAxisAlignment.center,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Icon(Icons.arrow_back_ios),
),
);
}
}
We can go back to the previous page via Navigator.of(context).pop() method.
Conclusion
Flutter's navigation acts like the stack.
If you visit a page, it is put on the stack.
In the same way, if you pop a page from the stack, it would be the most recently visited page.
'Dart (Flutter)' 카테고리의 다른 글
[Flutter] File Handling (0) | 2022.04.02 |
---|---|
[Flutter] Save Data using Shared Preferences (0) | 2022.04.01 |
[Flutter] How to Use Tab Bar Widget (0) | 2022.03.27 |
[Flutter] Adding Fonts to Flutter Application (0) | 2022.03.26 |
[Flutter] Adding Image to Flutter Application (0) | 2022.03.26 |
댓글