패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.2.1

vrouter

모든 플랫폼에서 네비게이션과 라우팅을 쉽게 만들어주는 네비게이션 패키지입니다. Navigator 2 위에 구축되었습니다.

30일 다운로드
285
좋아요
322
Pub 점수
55

패키지 설치

flutter pub add vrouter

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

vRouter는 모든 플랫폼에서 라우팅 및 탐색을 단순화하는 Flutter용 네비게이션 패키지입니다. Navigator 2 위에 구축되어 있으며, 중첩된 경로, 딥링크, 동적 경로 처리를 지원하는 선언적이고 유형 안전한 방식으로 앱 탐색을 관리합니다. 빌더플레이트를 줄이고 경로 관리의 확장성을 향상시켜 개발자 경험을 향상시킵니다. 이 패키지는 플랫폼에 관계없는 라우팅 로직을 지원하여 일관된 탐색 동작이 필요한 복잡한 애플리케이션에 적합합니다.

사용 사례

  • 중첩 탐색을 갖춘 단일 페이지 애플리케이션
  • 통합 라우팅이 필요한 크로스 플랫폼 앱
  • 딥링크 지원이 필요한 앱
  • 동적 세그먼트를 가진 복잡한 경로 계층
  • 네비게이션 흐름에서의 상태 관리 간소화

주요 기능

  • 선언적 라우팅 구성
  • 중첩 및 동적 경로 지원
  • 현대적인 라우팅을 위한 Navigator 2 기반
  • 플랫폼에 관계없는 탐색 로직
  • 타입 안전한 경로 정의
  • 기존 Flutter 앱과의 간편한 통합

적합한 대상

  • 확장 가능한 Flutter 앱을 개발하는 개발자
  • 복잡한 탐색 구조를 관리하는 팀
  • 딥 링크 및 URL 처리가 필요한 프로젝트
  • 일관된 라우팅을 갖춘 다중 플랫폼 대상 앱
  • 더 깔끔하고 유지보수하기 쉬운 네비게이션 코드를 원하는 개발자

고려 사항

  • Navigator 2 개념을 이해해야 합니다
  • 고급 사용 사례를 위해 추가 설정이 필요할 수 있습니다
  • 메인스트림 패키지에 비해 문서가 제한적
  • 구조화된 탐색이 필요한 앱에 가장 적합

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

VRouter logo

VRouter website Join our discord Github repo pub package


A Flutter package that makes navigation and routing easy.

Learn more at vrouter.dev

Here are a few things that this package will make easy:

  • Automated web url handling
  • Nesting routes
  • Transition
  • Advanced url naming
  • Reacting to route changing
  • Customizable pop events
  • And much more...

Index

Getting started

VRouter

VRouter is a widget which handles the navigation, it acts as a MaterialApp but also takes a routes arguments.

VRouter(
 debugShowCheckedModeBanner: false, // VRouter acts as a MaterialApp
 routes: [...], // Put your VRouteElements here
)

VRouteElements

VRouteElements are the building blocs of your routes.

Note that they are not widgets but the way you use them is very similar to widgets.

VWidget

VWidget maps a path to a widget:

VWidget(path: '/login', widget: LoginScreen())
VGuard

VGuard allows you to take actions when the route is accessed/leaved:

VGuard(
 beforeEnter: (vRedirector) async => , // Triggered when a route in stackedRoutes is first displayed
 beforeUpdate: (vRedirector) async => , // Triggered when a route in stackedRoutes is displayed but changes
 beforeLeave: (vRedirector, _) async => , // Triggered when VGuard is not part of a new route
 stackedRoutes: [...],
);
VRouteRedirector

VRouteRedirector redirects from a route to another:

VRouteRedirector(path: '/old/home', redirectTo: '/home')
VNester

VNester are used when you need to nested widgets instead of stacking them:

VNester(
 path: '/home',
 widgetBuilder: (child) => MyScaffold(body: child), // child will take the value of the widget in nestedRoutes
 nestedRoutes: [
   VWidget(path: 'profile', widget: ProfileScreen()), // path '/home/profile'
   VWidget(path: 'settings', widget: SettingsScreen()), // path '/home/settings'
 ],
)
VPopHandler

VPopHandler helps you control pop events:

VPopHandler(
 onPop: (vRedirector) async =>, // Called when this VRouteElement is popped
 onSystemPop: (vRedirector) async =>, // Called when this VRouteElement is popped by android back button
 stackedRoutes: [...],
)

Navigation

Navigating is easy, just access VRouter with context.vRouter and navigate:

context.vRouter.to('/home'); // Push the url '/home'

context.vRouter.toSegments(['home', 'settings']); // Push the url '/home/settings'

Useful notions

Composition

VRouteElements are designed like widgets: compose them to create the route you need.

Compose VRouteElements

To compose VRouteElements, use the stackedRoutes attribute (or the nestedRoutes attribute for VNester):

// Composing a VGuard and a VWidget
VGuard(
 beforeEnter: (vRedirector) async => !isLoggedIn ? vRedirector.to('/login') : null,
 stackedRoutes: [
   VWidget(path: '/home', widget: HomeScreen()),
 ],
)
Create custom VRouteElements

You can even create your own VRouteElement, as you extend VWidget. You just need to extends VRouteElementBuilder:

class HomeRoute extends VRouteElementBuilder {
 static String home = '/home';

 @override
 List<VRouteElement> buildRoutes() {
   return [
     VGuard(
       // LoginRoute.login = '/login' for example
       beforeEnter: (vRedirector) async => !isLoggedIn ? vRedirector.to(LoginRoute.login) : null,
       stackedRoutes: [
         VWidget(path: home, widget: HomeScreen()),
       ],
     ),
   ];
 }
}

and then use this VRouteElement as any other:

VRouter(
 routes: [
   HomeRoute(),
   ...
 ],
)

This can be used to:

  • Separate you different routes in different VRouteElement
  • Create reusable VRouteElement
  • Use static String to organise your paths

Note: you often want to use a shared VNester in different VRouteElementBuilders, for this specific use case, see vrouter.dev/Custom VRouteElement And Scaling

Path

Relative path

Paths can be relative: if you don’t start your path with /. If you use null, the path will be the one of the parent:

VNester(
 path: '/home',
 widgetBuilder: (child) => MyScaffold(body: child),
 nestedRoutes: [
   VWidget(path: null, widget: HomeScreen()), // Matches '/home'
   VWidget(path: 'settings', widget: SettingsScreen()), // Matches '/home/settings'
 ]
)
Path parameters

Paths can have path parameters, just use “:” in front of the path parameter’s name:

VWidget(path: '/user/:id', widget: UserScreen())

And access it in your widgets using:

context.vRouter.pathParameters['id'];
Wildcards

Wildcards are noted * and there are of one of two types:

  • Trailing wildcards (a path ending with *) will match everything
  • an in-path wildcard (a wildcard between slashes) will match one word
// Redirects any path to '/unknown'
VRouteRedirector(path: '*', redirectTo: '/unknown')
Path parameters regexp

Path parameters can use regex, just put the regex in parentheses. This is often used in VRedirector to redirect any unknown route:

// The path parameter name is “bookId” and it uses the regex “\d+” to match only digits
VWidget(path: r':bookId(\d+)', widget: BookScreen())

Note that such a VRedirector should be used as your last route otherwise it will always be matched.

Aliases

Use aliases for multiple paths:

// Matches '/settings' and '/other'
VWidget(path: '/settings', aliases: ['/other'], widget: SettingsScreen())

VRedirector

You often want to redirect or stop the current redirection in VGuard and VPopHandler. For that purpose, you get a VRedirector:

VGuard(
 beforeEnter: (vRedirector) async => !isLoggedIn ? vRedirector.to('/login') : null,
 stackedRoutes: [...],
)

VRouterData

VRouter contains data (such as the path or path parameters) that you might want to access in your widget tree. There are 2 ways of doing do:

// Use the context
context.vRouter

// Use the builder constructor of some VWidget or VNester
VWidget.builder(
  path: '/:id', 
  builder: (context, state) => Book(id: state.pathParameters['id'] as int),
)

Go Beyond

We have just scratched the surface of what VRouter can do. Here are a few other things which you might like.

Initial url

Maybe you want to redirect people to a certain part of your app when they first launch it, then use initialUrl:

VRouter(
 initialUrl: '/home',
 routes: [...],
)

Logs

By default, VRouter shows logs of every navigation events.

You can remove these logs using VLogs.none:

VRouter(
  logs: VLogs.none,
  routes: [...],
);

Named route

You might have to access a deeply nested VRouteElement and don’t want to have to write the full url. Just give a name to this VRouteElement:

VWidget(path: 'something', widget: SomeWidget(), name: 'deep')

And navigate using toNamed:

context.vRouter.toNamed('deep');

Transitions

You can either specify a default transition in VRouter, or a custom one in VWidget or VNester

VRouter(
 // Default transition
 buildTransition: (animation1, _, child) => FadeTransition(opacity: animation1, child: child),
 routes: [
   // The custom ScaleTransition will play for '/user'
   VWidget(
     path: '/user',
     widget: UsersScreen(),
     buildTransition: (animation1, _, child) => ScaleTransition(scale: animation1, child: child),
   )
   // The default FadeTransition will play for '/settings'
   VWidget(path: '/settings', widget: SettingsScreen()),
 ],
)

Much more

There is so much more that this package can do, check out the example or have a look at the vrouter.dev website for more documentation and more examples.

Also don’t hesitate to join us on discord !

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.