앱 개발 공부방

flutter - go_router 사용해서 라우팅하기 본문

FLUTTER

flutter - go_router 사용해서 라우팅하기

춘행이 2023. 12. 5. 15:27
728x90

flutter에서 페이지 이동을 할 때 기본적으로

Navigator.of(context).push(MaterialPageRoute(builder: (context) => const FirstPage()));

 이런 식으로 Navigator를 사용하는데 너무 길고 번거로워서 go_router 패키지를 사용해서 해보자

 

https://pub.dev/packages/go_router

 

go_router | Flutter Package

A declarative router for Flutter based on Navigation 2 supporting deep linking, data-driven routes and more

pub.dev

 

pubspec.yaml 파일에

go_router: ^12.1.1

추가해주고 pub get을 해준다

 

처음으로

final GoRouter router = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      name: 'home',
      builder: (context, state) => const MyHomePage(),
      routes: [
        GoRoute(
          path: 'second',
          name: 'second_page',
          builder: (context, state) => const SecondPage(),
          routes: [
            GoRoute(
              path: 'third',
              name: 'third_page',
              builder: (context, state) => const ThirdPage(),
            ),
          ]
        ),
      ],
    ),
  ],
);

라우터의 설정을 해준다

여기서 / 그저께에 secondPage가 있는데 / 아래에 있기 때문에 path에서 /를 제외하고 써줘도 된다 

 

 

그다음 materialApp 쪽을 설정하는데 MaterialApp을 사용 안 하고. router를 붙여서 사용한다

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      routeInformationProvider: router.routeInformationProvider,//route의 정보를 전달한다
      routeInformationParser: router.routeInformationParser,//uri등 go router에서 사용할수있는 형태로 파싱해주는 함수
      routerDelegate: router.routerDelegate,//위에서 파싱된 값으로 어떤 페이지를 보여줄지 정하는 함수
    );
  }
}

 

 

go , goNamed 함수

이동 할때 path를 써서 페이지 이동하는 go부터 알아본다

GestureDetector(
  onTap: () {
    context.go('/second');
  },
  child: Container(
    width: 100,
    height: 50,
    color: Colors.red,
    child: const Center(
      child: Text('go to second Page'),
    ),
  ),
),

위처럼 context.go('/second')를 호출해서 secondPage로 간다 

여기서 secondPage를 정의할때 path가 second라고 second로 호출하지 말고 / 페이지 아래에 있는 거 기 때문에 /second라 해준다

 

만약 /second 아래에도 또 페이지가 있으면 호출할때 /second/third/four~~ 이렇게 점점 길어질 거다 이를 대비해서 goNamed 함수로 간편하게 호출할 수 있다

GestureDetector(
  onTap: () {
    //context.go('/second');
    context.goNamed('third_page');
  },
  child: Container(
    width: 100,
    height: 50,
    color: Colors.red,
    child: const Center(
      child: Text('go to second Page'),
    ),
  ),
),

 

이렇게 라우트에서 설정할 때 설정한 name으로 호출하면 불편하게 /second/third로 호출하지 않고 간편하게 페이지 이동을 할 수 있다 

 

push , pushNamed 함수

go랑 동일하게 페이지 이동함수지만 차이점으론 go는 현재의 페이지를 대체하는 새로운 페이지로 렌더링이 되는 거면

p

 

pop

context.pop();

위 같은 코드로 뒤로 가기를 만들어줄 수 있다

 

728x90

'FLUTTER' 카테고리의 다른 글

flutter - provider 상태관리  (0) 2023.12.07
flutter - go_router 정보랑 같이 보내기  (1) 2023.12.05
flutter - 동기,비동기 프로그래밍  (1) 2023.12.05
flutter - 오버라이드  (1) 2023.12.05
flutter - Null Safety  (0) 2023.12.05
Comments