UI Guard Package

ui_guard

Pub Version Build GitHub Stars Flutter Website

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:

  • allowed
  • missingRoles
  • missingPermissions
  • failedCondition
  • reasonCode

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

Cron Schedule Diagram

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:

example/

The example application demonstrates:

  • Guard
  • GuardNotifier
  • Reactive guard updates
  • Role changes at runtime
  • Permission changes at runtime
  • AccessGuard
  • RoleBasedView
  • CombinedGuard
  • PolicyGuard
  • AccessPolicy
  • AccessDecision
  • onDecision diagnostics
  • TimedAccessGuard
  • ScheduleGuard
  • DeviceTypeGuard
  • AsyncGuard
  • 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

  • Guard
  • GuardNotifier
  • GuardConfig
  • RoleGuard
  • GuardUtils

Policies & Diagnostics

  • AccessPolicy
  • AccessDecision

Widgets

  • AccessGuard
  • RoleBasedView
  • CombinedGuard
  • PolicyGuard
  • TimedAccessGuard
  • ScheduleGuard
  • GuardListenableBuilder

๐Ÿ—๏ธ 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:

To contribute:

  1. Fork the repository
  2. Create a new branch
  3. Make your changes
  4. Add or update tests where applicable
  5. Commit your changes
  6. Push your branch
  7. Submit a pull request

โ˜• Support My Work

If you find ui_guard useful, consider supporting the project.

Buy Me a Coffee

Prefer mobile?

Scan the QR code below:

Buy Me a Coffee QR Code

Your support helps maintain and improve ui_guard. โค๏ธ


๐Ÿ‘ค Maintainer

MD. TANVIRUL ISLAM

GitHub: Tanvirul-swe


Made with โค๏ธ for the Flutter community.

Libraries

ui_guard