플러터 페이지 이동 (화면 전환)
2022.04.12
Named route로의 화면 전환
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: '플러터 페이지 이동',
// "/"으로 FirstScreen 으로 시작
initialRoute: '/',
routes: {
// "/" Route로 이동하면, FirstScreen 위젯을 생성
'/': (context) => FirstScreen(),
// "/second" route로 이동하면, SecondScreen 위젯을 생성
'/second': (context) => SecondScreen(),
// "/third" route로 이동하면, ThirdScreen 위젯을 생성
'/third': (context) => ThirdScreen(),
},
));
}
/* A 페이지 */
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PAGE A'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
child: Text('go to B'),
onPressed: () {
// Named route를 사용하여 두 번째 화면으로 전환
Navigator.pushNamed(context, '/second');
},
),
ElevatedButton(
child: Text('go to C'),
onPressed: () {
// Named route를 사용하여 세 번째 화면으로 전환
Navigator.pushNamed(context, '/third');
},
),
]),
),
);
}
}
/* B 페이지 */
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("PAGE B"),
),
body: Center(
child: TextButton(
onPressed: () {
Navigator.pushNamed(context, '/third');
},
child: Text('go to C'),
),
),
);
}
}
/* C 페이지 */
class ThirdScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("PAGE C"),
),
body: Center(
child: TextButton(
onPressed: () {
Navigator.pushNamed(context, '/');
// Navigator.pop(context); // 이전 페이지
},
child: Text('go to A'),
),
),
);
}
}