[Flutter]Getx Navigation(route관리)

Lia·2022년 8월 17일
0

🔵 Flutter

목록 보기
9/12
post-thumbnail

🔎기본 Navigation 살펴보기

import 'package:flutter/material.dart';

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

class FirstRoute extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page 1'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text("open page2"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}
class SecondRoute extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('page 2'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

이와 같이 Flutter에서 기존에 사용하던 Navigation은 Navigator에 context를 가지고 push 혹은 pop 등을 사용하는 방식이다.

Navigator.of(context).push(MaterialPageRoute(builder: (_) => FirstPage()));
Navigator.of(context).pop();
Navigator.of(context).pushAndRemoveUntil(MateriaPageRoute(builder: (_) => HomePage()), (route) => false);

🔎Getx Navigation

1.Getx설치하기
pubspec.yaml-dependencies 아래에 get을 추가하고 pub get

dependencies:
  get: ^4.6.5

2.getX를 사용하고 싶은 파일에 import하기

import 'package:get/get.dart';

3. MaterialApp을 GetMaterialApp으로 바꿔주기

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
    );
  }
}

아래와 같이 변경

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return GetMaterialApp(
    );
  }
}

GetX Navigation
GetX를 사용했을 때는 Navigation(Route 관리)어떻게 달라질까?

Get.to(FirstPage()); // 넘어가기
Get.back(); // 뒤로 가기
Get.offAll(HomePage()); // 홈으로 이동하고 Stack에 쌓인 페이지들 전부 삭제

기존 Navigation와 비교했을때 매우 간결하고 직관적이다. 자세히 비교해보자.

1.Route이동
기존

  ElevatedButton(
          child: Text("open page2"),
         onPressed: () {
            Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => SecondRoute()
           ),
         );

Getx

ElevatedButton(
              child: Text("open page2"),
              onPressed: () {
                Get.to( SecondRoute()); //페이지이동
              },
            );

2.전 페이지를 제외하고 이동하기
기존

 ElevatedButton(
            onPressed:() {
              Navigator.of(context).pushReplacement(
             MaterialPageRoute(
             builder:(_)=>SecondRoute(),
              ),
             );

Getx

ElevatedButton(
         onPressed:() {
           Get.off(SecondRoute());//전페이지로 돌아가지 못하게 하기
              },
            child: Text('Go back home!'),
          );

3.모든페이지 스택 삭제하기
기존-어떤 한 페이지를 띄우고 지금까지 봐왔던 페이지를 네비게이션 스택에서 모두 삭제하는 방식

ElevatedButton(
            onPressed:() {
              Navigator.of(context).pushAndRemoveUntil(
               MaterialPageRoute(
                builder:(_)=>SecondRoute(),
               ),
               (route) => false,
               );
              }
              child: Text(
             '모든 페이지 스택삭제'
              ),
             );

Getx

ElevatedButton(
            onPressed:() {
             Get.offAll(SecondRoute());
             },
             child: Text(
             '모든 페이지 스택삭제'
             ),
            );

4.뒤로가기
기존-if문을 써서 전 페이지가 있는지 확인해야한다. 그렇지 않으면 MaterialApp을 아예 나가서 까만화면이 나오게 됨

ElevatedButton(
            onPressed:() {
              if(Navigator.of(context).canPop())
              Navigator.of(context).pop();
           
             },
              child: Text(
             '뒤로가기'
             ),
            );

Getx-if문을 사용할 필요도 없이 라우팅이 안전하게 뒤로 갈수 없을 때는 작동하지 않도록 함

ElevatedButton(
            onPressed:() {
              Get.back();
             },
              child: Text(
             '뒤로가기'
             ),
            );

Argument를 보내고 다른 페이지에서 받아오기
[홈]

ElevatedButton(
            onPressed:() async{
              final resp = await Get.to(ThirdRoute());
              
              setState(() {
               returnVal = resp;
               });
             },
              child: Text(
             '리턴값받아오기'
             ),
            );

[ThirdRoute]

Row(
 children: [
Radio (
 groupValue : radioVal,
  value: 0,
  onchanged: (value){
   setState(() {
      radioVal = value;
            });
           },
          ),
           Text('0'),
          ],
         ),
         Row(
 children: [
Radio (
 groupValue : radioVal,
  value: 0,
  onchanged: (value){
   setState(() {
      radioVal = value;
            });
           },
          ),
           Text('1'),
          ],
         ),
         Row(
 children: [
Radio (
 groupValue : radioVal,
  value: 0,
  onchanged: (value){
   setState(() {
      radioVal = value;
            });
           },
          ),
           Text('2'),
          ],
         ),
         RaisedButton(
          onpressed:(){
            Get.back(result: radioVal);
               },
            child: Text('뒤로가기'),
             ),
            ],

뒤로가기 버튼을 누르면 Get.back을 실행한 후에 result라는 argument에 원하는 값을 집어넣으면 await하고 있던 전 route에서 값을 받을 수 있다.

profile
꺾이지않기ᕙ༼*◕_◕*༽ᕤ

0개의 댓글