👉 Flutter에서는 Navigator를 사용
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NextPage(),
),
);
👉 새 화면으로 이동
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return const MaterialApp(
home: FirstPage(),
);
}
}
// 첫 번째 화면
class FirstPage extends StatelessWidget {
const FirstPage({super.key});
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("첫 화면")),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
},
child: const Text("다음 화면으로"),
),
),
);
}
}
// 두 번째 화면
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("두 번째 화면")),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context); // 뒤로가기
},
child: const Text("뒤로가기"),
),
),
);
}
}
Navigator.pop(context);
👉 현재 화면 닫고 이전 화면으로 이동
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(name: "홍길동"),
),
);
class SecondPage extends StatelessWidget {
final String name;
const SecondPage({super.key, required this.name});
Widget build(BuildContext context) {
return Text(name);
}
}
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
print(result);
Navigator.pop(context, "데이터");
👉 이전 화면으로 값 전달
| 기능 | 코드 |
|---|---|
| 이동 | Navigator.push |
| 뒤로가기 | Navigator.pop |
| 값 전달 | 생성자 |
| 값 반환 | pop(context, 값) |
👉 build context 사용해야 함
final result = Navigator.push(...) // ❌
👉 값 못 받음
👉 push = 이동 / pop = 돌아가기