Flutter Navigation Advanced


Flutter 고급 내비게이션

Flutter에서 고급 내비게이션을 구현하는 방법에는 여러 가지가 있습니다. 여기서는 Navigator 2.0go_router 패키지를 사용하는 방법을 설명하겠습니다.

1. Navigator 2.0

Navigator 2.0은 더 유연하고 선언적인 내비게이션을 지원합니다. 이는 특히 웹과 데스크톱 애플리케이션에서 유용합니다.

Navigator 2.0 설정 및 사용

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _routerDelegate = MyRouterDelegate();
  final _routeInformationParser = MyRouteInformationParser();

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: _routerDelegate,
      routeInformationParser: _routeInformationParser,
    );
  }
}

class MyRouterDelegate extends RouterDelegate<RouteSettings>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<RouteSettings> {
  final GlobalKey<NavigatorState> navigatorKey;

  List<Page> _pages = [MaterialPage(child: HomePage())];

  MyRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();

  @override
  RouteSettings get currentConfiguration => _pages.last.arguments as RouteSettings;

  @override
  Future<void> setNewRoutePath(RouteSettings configuration) async {
    if (configuration.name == '/') {
      _pages = [MaterialPage(child: HomePage())];
    } else if (configuration.name == '/second') {
      _pages.add(MaterialPage(child: SecondPage()));
    }
    notifyListeners();
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: List.of(_pages),
      onPopPage: (route, result) {
        if (!route.didPop(result)) {
          return false;
        }
        _pages.removeLast();
        notifyListeners();
        return true;
      },
    );
  }
}

class MyRouteInformationParser extends RouteInformationParser<RouteSettings> {
  @override
  Future<RouteSettings> parseRouteInformation(RouteInformation routeInformation) async {
    final uri = Uri.parse(routeInformation.location!);
    if (uri.pathSegments.isEmpty) {
      return RouteSettings(name: '/');
    } else if (uri.pathSegments.length == 1 && uri.pathSegments[0] == 'second') {
      return RouteSettings(name: '/second');
    } else {
      return RouteSettings(name: '/');
    }
  }

  @override
  RouteInformation? restoreRouteInformation(RouteSettings configuration) {
    if (configuration.name == '/') {
      return RouteInformation(location: '/');
    } else if (configuration.name == '/second') {
      return RouteInformation(location: '/second');
    }
    return null;
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Router.of(context).routerDelegate.setNewRoutePath(RouteSettings(name: '/second'));
          },
          child: Text('Go to Second Page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Router.of(context).routerDelegate.setNewRoutePath(RouteSettings(name: '/'));
          },
          child: Text('Back to Home Page'),
        ),
      ),
    );
  }
}

2. go_router 패키지 사용

go_router는 선언적 내비게이션을 지원하는 패키지로, Flutter에서 더 쉽게 라우팅을 관리할 수 있게 해줍니다.

pubspec.yamlgo_router 추가

dependencies:
  flutter:
    sdk: flutter
  go_router: ^4.1.0

main.dart에서 go_router 사용

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

void main() => runApp(MyApp());

final GoRouter _router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => HomePage(),
    ),
    GoRoute(
      path: '/second',
      builder: (context, state) => SecondPage(),
    ),
  ],
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            context.go('/second');
          },
          child: Text('Go to Second Page'),
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            context.go('/');
          },
          child: Text('Back to Home Page'),
        ),
      ),
    );
  }
}

요약

  • Navigator 2.0: 더 유연하고 선언적인 내비게이션을 지원하며, 특히 웹과 데스크톱 애플리케이션에서 유용합니다.
  • go_router: 선언적 내비게이션을 지원하는 패키지로, Flutter에서 더 쉽게 라우팅을 관리할 수 있게 해줍니다.

이 예제들을 통해 Flutter 애플리케이션에서 고급 내비게이션 패턴을 구현할 수 있습니다. 실제 프로젝트에서는 이러한 예제를 기반으로 더 복잡한 라우팅 시나리오와 상태 관리를 추가하여 사용할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *