Flutter에서 여러 개의 페이지 간 이동을 구현하도록 돕는 Routes & Navigation에 대해 학습했다.
페이지를 Stack과 유사하게 push해서 쌓고, pop해서 다시 지워내는 방법으로 이동시킨다.
< 두개의 Route 간의 이동 >
Flutter 공식 문서 : [flutter.dev/docs/cookbook/navigation/navigation-basics]
class FirstRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Center(
child: ElevatedButton(
child: Text('Open route'),
onPressed: () {
// Navigate to second route when tapped.
},
),
),
);
}
}
class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to first route when tapped.
},
child: Text('Go back!'),
),
),
);
}
}
// Within the `FirstRoute` widget
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
}
// Within the SecondRoute widget
onPressed: () {
Navigator.pop(context);
}
< Navigate with named routes >
Flutter 공식 문서 : [flutter.dev/docs/cookbook/navigation/named-routes]
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: ElevatedButton(
child: Text('Launch screen'),
onPressed: () {
// Navigate to the second screen when tapped.
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Screen"),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Navigate back to first screen when tapped.
},
child: Text('Go back!'),
),
),
);
}
}
MaterialApp(
// Start the app with the "/" named route. In this case, the app starts
// on the FirstScreen widget.
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => FirstScreen(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/second': (context) => SecondScreen(),
},
);
initialRoute는 가장 첫번째로 나오는 Route를 의미한다. 즉 , 첫 페이지를 의미한다.
Routes 에 Map을 사용해여 각 Route들을 정의한다. 아래와 같은 의미를 가지고 있다.
'/' : (context) => FirstScreen
('/'로 Navigate할 때, FirstScreen Widget을 빌드하겠다.)
'/second': (context) => SecondScreen()
( '/second'로 Navigate할 때, SecondScreen Widget을 빌드하겠다.)
Route에 Name을 지정한 경우에는 Navigator.pushNamed(context, route Name)을 사용해 이동한다.
// Within the `FirstScreen` widget
onPressed: () {
// Navigate to the second screen using a named route.
Navigator.pushNamed(context, '/second');
}
반응형
'Flutter' 카테고리의 다른 글
Asynchronous Programming (0) | 2021.03.09 |
---|---|
[Dart] Enum (0) | 2021.03.09 |
[Flutter] Extract Widget (0) | 2021.03.09 |
[Dart] Final vs Const (0) | 2021.03.09 |
[Flutter] A RenderFlex overflowed by 58 pixels on the right (0) | 2021.03.04 |