* Navigator
- 두 화면 사이 이동
- 화면 분할 및 임포트
import 'package:flutter/material.dart';
import 'package:navigator_page/first_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstPage(),
);
}
}
* push로 새로운 화면 호출
- push를 이용해서 화면 전환
import 'package:flutter/material.dart';
import 'package:navigator_page/person.dart';
import 'package:navigator_page/second_page.dart';
class FirstPage extends StatelessWidget {
const FirstPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("First"),
),
body: ElevatedButton(
onPressed: () async {
final person = Person("홍길동", 20);
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(person:person),
),
);
print(result);
},
child: Text('다음 페이지로'),
style: ElevatedButton.styleFrom(
primary: Colors.orangeAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 0.0,
),
),
);
}
}
* pop으로 이전 화면으로 이동
- pop 메서드로 현재 화면을 종료하고 이전 화면으로 돌아감
import 'package:flutter/material.dart';
import 'package:navigator_page/person.dart';
class SecondPage extends StatelessWidget {
late final Person person;
SecondPage({required this.person});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second'),
),
body: ElevatedButton(
onPressed: (){
Navigator.pop(context, 'ok'); // 문자열을 이전 페이지로 전달함
},
child: Text('이전 페이지로'),
style: ElevatedButton.styleFrom(
primary: Colors.redAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 0.0,
),
),
);
}
}
class Person{
String? name;
int? age;
Person(this.name, this.age);
}