본문 바로가기
스파르타/Flutter

[Flutter] 네비게이션 - ( week 2 )

by bakcoding_sparta 2023. 4. 15.

앱 안에서 화면을 이동할 때 사용할 수 있다.

Flutter에서는 각 화면을 Route라고 부르며 이 라우터를 전환할 때는 Navigator를 사용한다.

 

// 페이지 이동
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => SecondPage()), // 이동하려는 페이지
);

// 현재 화면 종료
Navigator.pop(context); // 종료

 

Navigator

두 화면을 전환하는 예시

// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FirstPage(),
    );
  }
}

// 첫 번째 페이지
class FirstPage extends StatelessWidget {
  const FirstPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("홈"),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text("다음 페이지로 이동"),
          onPressed: () {
            // 페이지 이동
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondPage()),
            );
          },
        ),
      ),
    );
  }
}

// 두 번째 페이지
class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("두 번째 페이지 입니다!"),
      ),
      backgroundColor: Colors.amber,
      body: Center(
        child: ElevatedButton(
          child: Text("첫 번째 페이지로 되돌아가기"),
          onPressed: () {
            // 뒤로가기
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

 

Named Route

화면이 많아지는 경우에 사용할 수 있는 방식이다.

라우트 이름으로 화면을 전환할 수 있어 코드를 깔끔하게 관리할 수 있으며 이름을 상수로 정의하여 중복을 방지하고 유지보성을 향상할 수 있다.

 

MaterailApp 위젯의 routes 속성을 설정할 수 있다.

routes 속성은 May<String, WidgetBuilder> 형태로 Key는 라우트 이름, Value는 라우트에서 보여줄 위젯을 생성하는 콜백함수이다.

 

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/detail': (context) => DetailScreen(),
      },
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to detail screen'),
          onPressed: () {
            Navigator.pushNamed(context, '/detail');
          },
        ),
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detail'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go back to home screen'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

 

위 코드에서 MaterailApp 위젯의 route 속성을 설정하여 '/' 라우트와 '/detail' 라우트를 각각 화면에 연결시켜서 전환시킬 수 있다.