Recommanded Free YOUTUBE Lecture: <% selectedImage[1] %>

Contents

Route

대부분의 앱들은 다양한 유형의 정보들을 표시하기 위해서 하나 이상의 화면을 가지기 마련이다. 예를 들어 쇼핑 앱이라면, 첫 화면에는 제품의 목록을 카드형식으로 보여주고, 카드를 클릭하면 제품의 상세 정보 화면으로 이동 할 것이다. 여기에서 결제 버튼을 누르면 결제 화면으로 이동한다.

Flutter에서는 화면과 페이지를 routes라고 부른다. 안드로이드에서는 Activity, iOS에서는 ViewController이라고 한다. Flutter에서 route는 단지 위젯(widget)일 뿐이다. 결국 위젯과 위젯을 이동하는 것이 되겠다.

Flutter의 Navigator.push 와 Navigator.pop을 이용해서 페이지를 이동 할 수 있다.
  • Navigator.push() : 다음 route 로 이동
  • Navigator.pop() : 현재 route를 종료하고 이전 route 로 이동

개발 환경

  • 우분투 리눅스 20.10
  • Dart version 2.13
  • Flutter 2.1.0
  • vscode 1.55.1

두개의 경로를 만들어서 이동하기

FirstRoute 와 SecondRoute 두 개의 Route를 만든다. 앱을 FirstRoute가 첫 route로(앱 첫화면)로 실행된다. FirstRoute는 버튼을 하나 포함하고 있는데, 이 버튼을 클릭하면 SecondRoute route로 이동한다. SecondRoute route에서 버튼을 누르면 FirstRoute로 이동한다.

먼저 두 개의 route를 설정한다.
class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Route')),
      body: Center(
        child: ElevatedButton(
            child: Text('Second route'),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => SecondRoute()),
              );
            }),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Route')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Close route'),
        ),
      ),
    );
  }
}

Navigator.push()

Navigator.push()를 이용해서 route로 이동 할 수 있다. push()를 하면 새로운 route가 Stack에 쌓이게 된다. 각 위젯은 키보드, 마우스 입력을 받아서 처리하는 콜백을 제공한다. 예제 코드는 onPressed() 콜백을 이용해서 버튼 위젯 클릭하면 MaterialPageRoute를 이용해서 새로운 위젯으로 넘어가게 했다.

onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
  );
}),

Navigator.pop()

Navagator.pop() 메서드를 이용하면 현재 route 스택에서 현재 route를 제거 할 수 있다. 결과적이로 이전 route(페이지)로 이동하게 될 것이다.
child: ElevatedButton(
   onPressed: () {
      Navigator.pop(context);
   },
child: Text('Close route'),

완전한 코드

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: "Navigation Basics",
    home: FirstRoute(),
  ));
}

class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Route')),
      body: Center(
        child: ElevatedButton(
            child: Text('Second route'),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => SecondRoute()),
              );
            }),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Route')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Close route'),
        ),
      ),
    );
  }
}

정리

Widget

Flutter의 모든 것은 위젯(Widget)이다. 핵심 아이디어는 위젯에 UI를 구축하는 것이다. 각각의 위젯은 다른 위젯과 독립적인데, 이 위젯은 route로 이동 할 수 있다.

Route

Route는 위젯의 UI 표현과 코드를 구성하는데 도움이 되는 것들의 정의다. 루트 위젯에 등록된 모든 route 들은 애플리케이션의 어느 지점에서든지 이동 할 수 있다.

애플리케이션 화면은 두 개의 라우팅 옵션을 이용해서 페이지간 이동을 설정 할 수 있다.
  1. 정의된(defined) route의 라우팅
  2. 정의되지 않은 route의 라우팅

Defined Routes

Flutter 프로젝트를 시작하게 되면, 개발자는 아래와 같은 형식으로 페이지간 이동을 정의하게 될 것이다.

 Defined Routes

main.dart 파일에서 루트 위젯에서 route를 정의 할 수 있다.
// main.dart
import 'package:flutter/material.dart'; 
import 'package:flutter/widgets.dart'; // starting point of the application 
void main() => runApp(     // root widget    
    MaterialApp( 
        title: "TestApplication", 
        initialRoute: "/", 
        routes: { 
            "/".     : (context) => MainWidget(), 
            "/detail": (context) => DetailWidget(), 
            "/test"  : (context) => TestWidget(), 
        }, 
    ) 
);
이제 루트 위젯에 등록된 route는 애플리케이션의 어느 곳에서든 호출 할 수 있다.

 route navigation

호출하기 원하는 route는 push(), pop()으로 간단하게 호출 할 수 있다.

Without defined Routes

Route를 미리 정의하지 않고 필요 할 때 호출 할 수 있다. 역시 push(), pop()으로 호출하면 된다. 예제 코드가 사용하는 방식이다.

Navigator.push(
	context,
	MaterialPageRoute(builder: (context) => DetailWidget()),
)

pop() 메서드로 원래 페이지로 되돌아올 수 있다.
Navigator.pop(context);