Flutter Route Guard
A platform-agnostic Flutter package for guarding routes based on asynchronous state.
flutter_route_guard makes it easy to protect routes in your Flutter application, handling loading, error, and data states gracefully. It is designed to work with any router.
Features
- Async State Handling: Built-in support for loading, error, and data states via
GuardAsyncValue. - Platform Agnostic: Works with any state management solution.
- Flexible Redirection: Automatically redirects unauthorized users to a fallback path.
- Router Independent: purely widget-based, integrating seamlessly with your existing navigation setup.
Usage
1. Define your Guard State
Wrap your state in GuardAsyncValue.
// Example using a simple ValueNotifier or similar
GuardAsyncValue<bool> authState = const GuardAsyncData(true); // User is authenticated
2. Wrap your Route
Use the RouteGuard widget to protect a page.
RouteGuard(
state: authState, // Your async state
destinationPath: '/dashboard', // Where we are trying to go
currentPath: currentPath, // The current location (from your router)
fallbackPath: '/login', // Where to go if denied
onRedirect: (context, path) {
// Navigate using your router, e.g., Navigator.pushNamed(context, path);
// or specific router method
},
loadingWidget: const CircularProgressIndicator(), // Optional
child: DashboardScreen(),
)
Installation
Add flutter_route_guard to your pubspec.yaml:
dependencies:
flutter_route_guard: ^0.0.1
Libraries
- domain/base_async_value
- A platform-agnostic representation of an asynchronous value state.
- flutter_route_guard
- A platform-agnostic Flutter package for guarding routes based on asynchronous state.
- presentation/route_guard
- This library provides the RouteGuard widget.