ui_guard
Widgets that make role, permission, condition, policy, and time-based UI control
simple, scalable, and flexible.
Built entirely in Dart to help you create smarter, access-aware Flutter applications.
โจ ui_guard works seamlessly with any role management logic or state management approach.
๐ Why use ui_guard?
In many Flutter applications, you need to control access to certain parts of the UI.
For example:
- Show admin settings only to administrators
- Display upgrade buttons for guest or free users
- Hide actions when a user does not have the required permission
- Enable UI only when multiple access conditions are satisfied
- Reuse the same authorization rules across multiple screens
- Display UI only during a specific start/end time
- Enable features according to cron-style schedules
- React automatically when roles or permissions change
- Diagnose exactly why access was denied
ui_guard makes these scenarios simple and declarative using Dart.
โจ Features
- โ Guard widgets or entire screens based on roles
- ๐ Permission-based access control
- ๐งฉ Combine roles, permissions, and runtime conditions
- โป๏ธ Reusable authorization policies with
AccessPolicy - ๐ Reactive role and permission updates with
GuardNotifier - ๐ Access diagnostics with
AccessDecision - ๐งช Developer override mode for development and testing
- ๐ฆ Pure Dart โ no platform-specific dependencies
- โป๏ธ Works with any state management approach
- โฑ๏ธ Start/end time-based UI control
- ๐ Cron-style scheduled UI access
- ๐ Optional UTC schedule evaluation
- ๐ฑ Responsive and device-based UI control with
DeviceTypeGuard - โก Asynchronous role loading with
AsyncGuard(APIs, Secure Storage, Firebase/Auth) - ๐ Access decision callbacks for logging and debugging
๐ฆ Installation
Add ui_guard to your pubspec.yaml:
dependencies:
ui_guard: ^1.2.0
Then run:
flutter pub get
Import the package:
import 'package:ui_guard/ui_guard.dart';
๐ Quick Start
Use GuardNotifier when you want the UI to rebuild automatically after role or permission updates.
import 'package:flutter/material.dart';
import 'package:ui_guard/ui_guard.dart';
final guard = GuardNotifier()
..setUserRoles(['guest'])
..setUserPermissions([]);
class ExampleView extends StatelessWidget {
const ExampleView({super.key});
@override
Widget build(BuildContext context) {
return AccessGuard(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['admin'],
builder: (_) => const Text('Admin content'),
fallbackBuilder: (_) => const Text('Access denied'),
);
}
}
When the roles or permissions inside GuardNotifier change, widgets using:
rebuildListenable: guard
can automatically rebuild.
๐งญ Which Widget Should You Use?
| Need | Widget |
|---|---|
| Show/hide a full section or page by role | AccessGuard |
| Show/hide a small inline widget by role | RoleBasedView |
| Require roles + permissions + runtime condition | CombinedGuard |
| Reuse named authorization rules across screens | PolicyGuard + AccessPolicy |
| Enable content only in a start/end time window | TimedAccessGuard |
| Enable content using a cron schedule | ScheduleGuard |
| Show/hide UI based on device type / screen size | DeviceTypeGuard |
| Load roles asynchronously from API / storage | AsyncGuard |
๐ง Core API
๐น 1. Define Access State
ui_guard provides both non-reactive and reactive guard state.
Basic โ Guard
Use Guard when automatic UI rebuilding is not required.
final guard = Guard();
guard.setUserRoles(['admin']);
guard.setUserPermissions(['users.edit']);
You can access the current roles:
print(guard.currentRoles);
Reactive โ GuardNotifier
For Flutter UI, GuardNotifier is recommended when roles or permissions can change while the application is running.
final guard = GuardNotifier();
guard.setUserRoles(['admin']);
guard.setUserPermissions(['users.edit']);
Use it with:
rebuildListenable: guard
Example:
AccessGuard(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['admin'],
builder: (_) => const Text('Admin Panel'),
fallbackBuilder: (_) => const Text('Access Denied'),
);
๐ Role-Based Access
๐น 2. AccessGuard
Use AccessGuard when you want to protect a complete widget, section, or page.
AccessGuard(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['admin'],
builder: (_) => const AdminPanel(),
fallbackBuilder: (_) => const Text('No access'),
);
If you are using the non-reactive Guard, simply remove:
rebuildListenable: guard
Example:
AccessGuard(
guard: guard,
requiredRoles: const ['admin'],
builder: (_) => const Text('Admin Panel'),
fallbackBuilder: (_) => const Text('Access Denied'),
);
๐น 3. RoleBasedView
Use RoleBasedView when you need to show or hide a smaller inline widget.
RoleBasedView(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['guest'],
child: const Text('Guest banner'),
fallback: const SizedBox.shrink(),
);
Another example:
RoleBasedView(
guard: guard,
requiredRoles: const ['admin', 'moderator'],
child: const Text('Admin & Moderator Content'),
fallback: const Text(
'You do not have permission to view this content.',
),
);
๐น 4. RoleGuard
RoleGuard provides utility methods for common role checks.
RoleGuard.hasAnyRole(
['admin'],
['admin', 'user'],
); // true
RoleGuard.hasAllRoles(
['admin', 'editor'],
['admin'],
);
Use these utilities when you need role checking outside guard widgets.
๐งฉ Combined Access Conditions
๐น 5. CombinedGuard
Use CombinedGuard when access depends on multiple requirements.
It can combine:
- Roles
- Permissions
- Runtime conditions
Example:
CombinedGuard(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['manager'],
requiredPermissions: const ['team.edit'],
condition: () => isInternalMode,
builder: (_) => const TeamEditor(),
fallbackBuilder: (_) => const Text('Requirements not met'),
);
This is useful when a role alone is not enough to determine whether content should be available.
For example:
CombinedGuard(
guard: guard,
requiredRoles: const ['manager'],
requiredPermissions: const ['edit_team'],
condition: () => organization.isInternalMode,
builder: (_) => const TeamEditor(),
fallbackBuilder: (_) => const Text('Access Restricted'),
);
โป๏ธ Reusable Access Policies
๐น 6. AccessPolicy + PolicyGuard
When the same authorization rule is used in multiple places, define it once as an AccessPolicy.
const manageUsersPolicy = AccessPolicy(
name: 'manage_users',
requiredRoles: ['admin'],
requiredPermissions: ['users.edit'],
);
Then reuse the policy:
PolicyGuard(
guard: guard,
rebuildListenable: guard,
policy: manageUsersPolicy,
builder: (_) => const Text('User manager'),
fallbackBuilder: (_) => const Text('No access'),
);
This keeps authorization rules centralized and avoids repeating the same role and permission requirements across your application.
Example use cases include:
- User management
- Payment administration
- Moderator tools
- Organization settings
- Restricted reports
- Feature management
๐ Access Diagnostics
๐น 7. AccessDecision
Sometimes hiding a widget is not enough โ you also need to understand why access was denied.
The onDecision callback provides an AccessDecision.
It can include information such as:
allowedmissingRolesmissingPermissionsfailedConditionreasonCode
Example:
CombinedGuard(
guard: guard,
requiredRoles: const ['manager'],
onDecision: (decision) {
if (!decision.allowed) {
debugPrint('Missing roles: ${decision.missingRoles}');
debugPrint(
'Missing permissions: ${decision.missingPermissions}',
);
debugPrint(
'Failed condition: ${decision.failedCondition}',
);
debugPrint('Reason code: ${decision.reasonCode}');
}
},
builder: (_) => const Text('Manager area'),
fallbackBuilder: (_) => const Text('Denied'),
);
This is especially useful for:
- Debugging authorization problems
- Analytics
- Logging
- Access auditing
- Development diagnostics
๐งช Developer Override Mode
During development or automated/manual testing, you may temporarily bypass guard restrictions.
GuardConfig.developerOverrideEnabled = true;
When enabled, guard checks are bypassed.
โ ๏ธ Developer override should only be used during development or testing.
Before production, make sure it is disabled:
GuardConfig.developerOverrideEnabled = false;
โฑ๏ธ Time-Based Access
๐น 8. TimedAccessGuard
Use TimedAccessGuard when content should only be available between a start and end time.
Ideal for:
- ๐ Limited-time offers
- โก Flash sales
- ๐งช Beta or trial features
- ๐ง Maintenance notices
- ๐ Event-specific content
- ๐๏ธ Daily or weekly deals
- ๐ข Time-based announcements
- ๐ข Business-hour features
Example:
TimedAccessGuard(
start: DateTime(2026, 3, 29, 9),
end: DateTime(2026, 3, 29, 18),
checkInterval: const Duration(seconds: 1),
onTimeUpdate: (remaining) {
debugPrint(
'Remaining: ${remaining.inSeconds}s',
);
},
builder: (_) => const Text('Offer active'),
fallbackBuilder: (_) => const Text('Offer closed'),
);
Another example:
TimedAccessGuard(
start: DateTime(2026, 7, 18, 9),
end: DateTime(2026, 7, 18, 13),
checkInterval: const Duration(seconds: 1),
onTimeUpdate: (remaining) {
debugPrint(
'โฑ๏ธ Time left: ${remaining.inSeconds}s',
);
},
builder: (_) => const PromoBanner(),
fallbackBuilder: (_) => const SizedBox.shrink(),
);
๐ Scheduled Access with ScheduleGuard
ScheduleGuard controls UI visibility using cron-style schedules.
Example:
ScheduleGuard(
schedule: '*/15 9-17 * * MON-FRI',
useUtc: true,
checkInterval: const Duration(minutes: 1),
builder: (_) => const Text('Business hours'),
fallbackBuilder: (_) => const Text('Outside business hours'),
);
Another example:
ScheduleGuard(
schedule: '0 9 * * 1-5',
builder: (_) => const Text('Business is open!'),
fallbackBuilder: (_) => const Text('Closed right now.'),
);
๐ง How Cron Scheduling Works
ScheduleGuard supports the standard 5-field cron format:
minute hour day month weekday
Supported cron capabilities
- Wildcards
*
- Lists
1,2,3
- Ranges
1-5
- Steps
*/5
- Month aliases
JAN
FEB
MAR
- Day aliases
MON-FRI
- Cron macros such as:
@daily
@weekly
@hourly
The guard can automatically re-evaluate according to the provided:
checkInterval
You can also choose whether scheduling should be evaluated using UTC:
useUtc: true
๐ ScheduleGuard Use Cases
ScheduleGuard can be useful for:
- ๐ Enable features during business hours
- ๐ท๏ธ Display promotional banners during selected hours
- ๐ ๏ธ Hide functionality during maintenance windows
- โฐ Enable actions only at specific scheduled times
- ๐ข Display scheduled announcements
- ๐ Enable weekday-only functionality
- ๐ Run time-limited promotions
- ๐ฌ Enable customer support/chat during office hours
๐ฑ Device & Screen-Based Access with DeviceTypeGuard
DeviceTypeGuard shows or hides UI elements based on the device type and screen size the app is running on.
โจ Benefits & Use Cases
- ๐ฑ Show a simplified layout on phones, and an advanced one on tablets or desktops
- ๐ Hide certain features on web (e.g., camera, hardware-specific tools) or enable web-only controls
- ๐ Conditional rendering of widgets based on responsive screen breakpoints
- ๐ป Platform-specific UI gating (Android, iOS, macOS, Windows, Linux, Web)
- ๐จ Supports responsive design logic directly in your widget tree
๐ง Example: Responsive Layout (Issue #9 Planned API)
DeviceTypeGuard(
allowedDevices: ['mobile', 'tablet'],
builder: (_) => const MobileView(),
fallbackBuilder: (_) => const DesktopView(),
);
๐ง Example: Using DeviceType Enum
DeviceTypeGuard(
allowedDevices: [DeviceType.desktop, DeviceType.web],
builder: (_) => const DesktopOrWebHeader(),
fallbackBuilder: (_) => const MobileHeader(),
);
๐ง Example: Custom Breakpoints & Overrides
DeviceTypeGuard(
allowedDevices: const ['tablet', 'desktop'],
breakpoints: const DeviceBreakpoints(
mobileBreakpoint: 500,
tabletBreakpoint: 900,
),
builder: (_) => const ExpandedDashboard(),
fallbackBuilder: (_) => const CompactDashboard(),
);
โก Asynchronous Role Loading with AsyncGuard
AsyncGuard allows ui_guard to work seamlessly when user roles or permissions are not available immediately โ such as when fetching from:
- ๐ Secure storage / SharedPreferences
- ๐ Remote backend REST / GraphQL APIs
- ๐ฅ Firebase Auth / Supabase / OAuth identity providers
๐ง Example: Issue #5 Planned API
AsyncGuard(
roleFuture: loadUserRolesFromServer(),
builder: (context, roles) => AccessGuard(
guard: Guard()..setUserRoles(roles),
requiredRoles: const ['admin'],
builder: (_) => const Text("Admin Dashboard"),
fallbackBuilder: (_) => const Text("Access Denied"),
),
);
๐ง Example: Direct Role Gating with AsyncGuard.guard
AsyncGuard.guard(
roleFuture: loadUserRolesFromServer(),
requiredRoles: const ['admin'],
loadingBuilder: (_) => const Center(child: CircularProgressIndicator()),
builder: (_) => const AdminDashboard(),
fallbackBuilder: (_) => const AccessDeniedView(),
);
๐ง Example: Programmatic Async Evaluation
final hasAccess = await GuardUtils.evaluateAsync(
roleFuture: fetchUserRoles(),
requiredRoles: const ['admin'],
);
๐ฑ Example App
A complete working example is available in:
The example application demonstrates:
GuardGuardNotifier- Reactive guard updates
- Role changes at runtime
- Permission changes at runtime
AccessGuardRoleBasedViewCombinedGuardPolicyGuardAccessPolicyAccessDecisiononDecisiondiagnosticsTimedAccessGuardScheduleGuardDeviceTypeGuardAsyncGuard- Developer override behavior
You can explore the example project to understand how the different guards can work together in a real Flutter application.
๐งฉ Common Use Cases
| Use Case | Example |
|---|---|
| Admin-only screens | requiredRoles: ['admin'] |
| Guest-specific UI | Display upgrade or login actions |
| Feature restrictions | Hide paid features from free users |
| Auth state UI | Show different actions based on access state |
| Nested permissions | Combine moderator/admin roles |
| Permission-based actions | Require permissions such as users.edit |
| Read-only vs edit access | Conditionally render edit buttons or fields |
| Subscription tiers | Control access for free, premium, or pro users |
| Combined logic | Roles + permissions + runtime conditions |
| Reusable policies | Share authorization rules with AccessPolicy |
| Access diagnostics | Detect missing roles or permissions |
| Developer override | Skip restrictions during development/testing |
| Time-based access | Use TimedAccessGuard |
| Scheduled access | Use ScheduleGuard |
| Business hours | Enable UI using cron schedules |
| Promotions | Show content only during campaign periods |
๐ API Exports
The main package export is:
import 'package:ui_guard/ui_guard.dart';
It includes the primary APIs required to use the package.
Core
GuardGuardNotifierGuardConfigRoleGuardGuardUtils
Policies & Diagnostics
AccessPolicyAccessDecision
Widgets
AccessGuardRoleBasedViewCombinedGuardPolicyGuardTimedAccessGuardScheduleGuardGuardListenableBuilder
๐๏ธ Example Architecture
A common application structure could look like:
final guard = GuardNotifier();
void configureUserAccess() {
guard.setUserRoles([
'manager',
]);
guard.setUserPermissions([
'team.view',
'team.edit',
]);
}
Then anywhere in your application:
AccessGuard(
guard: guard,
rebuildListenable: guard,
requiredRoles: const ['manager'],
builder: (_) => const ManagerDashboard(),
fallbackBuilder: (_) => const AccessDeniedView(),
);
For reusable business rules:
const editTeamPolicy = AccessPolicy(
name: 'edit_team',
requiredRoles: ['manager'],
requiredPermissions: ['team.edit'],
);
Use it wherever required:
PolicyGuard(
guard: guard,
rebuildListenable: guard,
policy: editTeamPolicy,
builder: (_) => const EditTeamButton(),
fallbackBuilder: (_) => const SizedBox.shrink(),
);
This keeps your UI access logic clean, reusable, and easier to maintain as the application grows.
๐ฌ Contributing
Contributions are welcome! ๐
Useful links:
- ๐ GitHub Repository
- ๐ Report an Issue
To contribute:
- Fork the repository
- Create a new branch
- Make your changes
- Add or update tests where applicable
- Commit your changes
- Push your branch
- Submit a pull request
โ Support My Work
If you find ui_guard useful, consider supporting the project.
Prefer mobile?
Scan the QR code below:
Your support helps maintain and improve ui_guard. โค๏ธ
๐ค Maintainer
MD. TANVIRUL ISLAM
GitHub: Tanvirul-swe
Made with โค๏ธ for the Flutter community.