본문 바로가기
Flutter

Flutter에서 go_router를 사용하여 기본 페이지 전환 설정하기

by 난타코다옹 2023. 10. 5.

원인: go_router는 페이지 전환을 설정하는 pageBuilder 속성을 제공합니다. 그러나 이 속성을 사용하여 각 페이지마다 전환을 설정하는 것은 매우 번거롭고 중복적인 작업입니다. 따라서 모든 페이지에 대해 기본 페이지 전환을 설정하는 방법이 필요합니다.

해결: go_router의 GoRouter 위젯에 대한 transitionBuilder 속성을 사용하여 모든 페이지에 대한 기본 페이지 전환을 설정할 수 있습니다. 이 속성은 페이지 전환을 생성하는 함수를 제공합니다. 따라서 모든 페이지에 대해 동일한 페이지 전환을 설정하려면 이 속성을 사용하면 됩니다.

GoRouter(
  // ...
  transitionBuilder: (context, child) {
    return CustomTransitionPage<void>(
      child: child,
      transitionsBuilder: (context, animation, secondaryAnimation, child) =>
          FadeTransition(opacity: animation, child: child),
    );
  },
);

위의 코드에서 CustomTransitionPage는 go_router의 pageBuilder와 동일한 역할을 합니다. 따라서 모든 페이지에 대해 기본 페이지 전환을 설정하려면 transitionBuilder에 CustomTransitionPage를 사용하여 페이지 전환을 생성하면 됩니다.

예시 코드:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'go_router Default Page Transition Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routerDelegate: GoRouter(
        // Define your routes here
        routes: [
          GoRoute(
            path: '/',
            pageBuilder: (context, state) => const HomeScreen(),
          ),
          GoRoute(
            path: '/login',
            pageBuilder: (context, state) => const LoginScreen(),
          ),
          GoRoute(
            path: '/profile',
            pageBuilder: (context, state) => const ProfileScreen(),
          ),
        ],
        // Define the default page transition here
        transitionBuilder: (context, child) {
          return CustomTransitionPage<void>(
            child: child,
            transitionsBuilder: (context, animation, secondaryAnimation, child) =>
                FadeTransition(opacity: animation, child: child),
          );
        },
      ).delegate(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Home Screen'),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/login');
              },
              child: const Text('Go to Login'),
            ),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/profile');
              },
              child: const Text('Go to Profile'),
            ),
          ],
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Login'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Login Screen'),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/');
              },
              child: const Text('Go to Home'),
            ),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/profile');
              },
              child: const Text('Go to Profile'),
            ),
          ],
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Profile'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Profile Screen'),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/');
              },
              child: const Text('Go to Home'),
            ),
            ElevatedButton(
              onPressed: () {
                GoRouter.of(context).go('/login');
              },
              child: const Text('Go to Login'),
            ),
          ],
        ),
      ),
    );
  }
}

결론: go_router를 사용하여 모든 페이지에 대해 기본 페이지 전환을 설정하는 것은 매우 간단합니다. transitionBuilder 속성을 사용하여 페이지 전환을 생성하는 함수를 정의하면 됩니다. 이를 통해 모든 페이지에 대해 일관된 페이지 전환을 적용할 수 있으며, 코드의 중복을 줄일 수 있습니다. 이를 통해 Flutter 애플리케이션의 성능과 유지 보수성을 향상시킬 수 있습니다.