본문 바로가기

개발 기록/플러터

플러터 튜토리얼 - 화면 이동 (Navigator, routes)

안녕하세요 :)

이번 시간에는 스크린을 이동하는 방법에 대해서 학습을 하도록 하겠습니다.

화면이 몇 개 없는 경우에는 Navigator만을 사용하여 화면 전환을 하셔도 되겠지만, 화면(스크린)이 많아지는 경우에는 routes를 사용하여 화면들을 등록해 놓고 필요에 따라서 호출을 하실 수 있어요.

Navigator부터 살펴보도록 하겠습니다.

 

1. Navigator

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstPage(),
    );
  }
}

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

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Page"),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text("이전 페이지로 돌아가기"),
          onPressed: (){
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

 

크게 어려운 내용은 없어요. Navigator는 화면 이동을 위해서 정형화된 방식으로 사용을 하는데요. 이동하는 화면으로 Navigator를 활용하여 push를 해주고, 이전 화면으로 이동하실 때는 push를 해주시면 되겠습니다.

 

2. routes 사용

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/firstpage',
      routes: {
        '/firstpage': (context) => FirstPage(),
        '/secondpage': (context) => SecondPage()
      },
    );
  }
}

class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("First Page"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: (){
            Navigator.pushNamed(
              context,
              '/secondpage'
            );
          },
          child: const Text("다음 페이지로 이동"),
        ),
      ),
    );
  }
}

 

routes를 사용하면 클래스 이름을 사용하는 대신, 내가 정해준 별명을 사용할 수가 있습니다.

 

 

[0] navigation 설명

https://docs.flutter.dev/ui/navigation

 

[1] Navigator API

https://api.flutter.dev/flutter/widgets/Navigator-class.html

 

[2] cook book

https://docs.flutter.dev/cookbook#navigation

 

[3] 플러터 샘플 프로젝트

https://flutter.github.io/samples/#