프로그램/FLUTTER

[Flutter] 플러터 go_router 세팅 및 설정하기

프뚜 2023. 9. 6. 10:00
728x90
반응형
SMALL

안녕하세요! 프뚜입니다.

bloc에 대해 포스팅합니다.


OS: Windows 10

Dart: Dart SDK version: 3.0.6 (stable) (Tue Jul 11 18:49:07 2023 +0000) on "windows_x64"

Flutter: Flutter 3.10.6


# go_router 설치하기

flutter pub add go_router

프로젝트 경로에서 위 명령어를 실행합니다.


# routes 파일 생성하기

class AppRoutes {
  static const String root = '/';
}

router 경로를 지정 할 class 파일을 생성합니다.


# router 파일 생성하기

import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:johdaetgoo_flutter/commons/routers/app_routes.dart';
import 'package:johdaetgoo_flutter/pages/subscriber/views/test_page.dart';

final GlobalKey<NavigatorState> rootNavKey = GlobalKey<NavigatorState>();

class AppRouter {
  GoRouter router = GoRouter(
    debugLogDiagnostics: true,
    navigatorKey: rootNavKey,
    routes: [
      ShellRoute(
        // 2023.08.25[프뚜]: init page 설정
        builder: (context, state, child) => const TestView(),
        routes: [
          GoRoute(
              path: AppRoutes.root,
              pageBuilder: (context, state) =>
              const NoTransitionPage(child: TestView())),
        ],
      )
    ],
  );
}

builder에서 init page를 설정합니다. routes에 GoRoute 정보 들을 입력합니다.


# 화면 이동하기

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:johdaetgoo_flutter/commons/routers/app_routes.dart';

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

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        // 2023.08.29[프뚜]: 화면 이동
        context.go(AppRoutes.root);

        // 2023.08.29[프뚜]: 화면 쌓기
        context.push(AppRoutes.root);

        // 2023.08.29[프뚜]: 현재 화면 닫기
        Navigator.pop(context);
      },
      child: const Text('클릭'),
    );
  }
}

크게 3가지를 많이 사용합니다.

go는 history를 남기지 않고 이동합니다.

push는 히스토리를 남기면서 블럭을 쌓는 것 처럼 이동됩니다.

pop은 쌓인 push의 가장 윗 화면부터 지워집니다.


플러터 화면 이동 제어에 대해 포스팅되었습니다.

728x90
반응형
LIST