반응형

우리는 일반적으로 앱에서 화면 전환을 심심치 않게 볼 수 있다. 이 기능을 위해서 flutter에는 Navigator라는 것이 존재하는데. 그것의 사용방법에 대해서 알아 보겠다.

 

1. Navigator의 원리 및 기본 코드

우선 Navigator는 Stack 방식으로 작동하기 때문에 push와 pop으로 작동시켜야 한다.

1
2
3
4
5
6
7
8
onPressed: (){ //주로 버튼을 눌렀을때 실행하는 경우가 많음
  Navigator.push(context1, MaterialPageRoute( //context1은 현재 page의 Buildcontext
    builder: (context)=>SecondPage())); //context는 고정, SecondPage는 넘어가고 싶은 page의 이름
},
 
onPressed: (){
  Navigator.pop(context2); //context2는 현재 page의 Buildcontext
},
cs

1-4줄까지는 push하는 방법이고, 6-8줄까지는 pop하는 방법이다. 

 

2. Navigator 예시 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import 'package:flutter/material.dart'//flutter의 package를 가져오는 코드 반드시 필요
 
void main() => runApp(MyApp()); //main에서 MyApp이란 클래스를 호출한다.
 
class MyApp extends StatelessWidget { //MyApp 클래스 선언
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'my first app',
      home: FirstPage(),
    );
  }
}
class FirstPage extends StatelessWidget {
  Widget build(BuildContext context1) {
    return Scaffold(
      appBar: AppBar(
        title: Text('first page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('go to second page'),
          onPressed: (){
            Navigator.push(context1, MaterialPageRoute(
                builder: (context)=>SecondPage()));
          },
        ),
      ),
    );
  }
}
class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context2) {
    return Scaffold(
      appBar: AppBar(
        title: Text('second page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('go to firsts page'),
          onPressed: (){
           Navigator.pop(context2);
          },
        ),
      ),
    );
  }
}
 



왼쪽 화면의 버튼을 누르면 오른쪽 화면으로 넘어가고, 오른쪽 버튼을 누르면 왼쪽화면으로 넘어간다.

 

3. Navigator의 사용 주의점, 알아두면 좋은 점

1. MaterialApp이 Navigator에 직접 push되는 클래스 내부에 있으면(FirstPage, SecondPage) 오류가 발생한다.

 

2. builder 뒤에 context는 사용하지 않으므로, 사용하지 않을때는 _ 으로 대체해두면 좋다.

 

3. 첫 page를 제외하고는 appBar의 뒤로가기 버튼이 자동생성되고 pop이 들어가나, appBar를 만들지 않을경우 생성되지 않는다.

 

 

flutter navigtor 추가 팁: 맨 처음 꺼 빼고 전부 pop 하는방법

Navigator.of(context).popUntil((route) => route.isFirst); 

 

 

 

반응형

+ Recent posts