ui_guard 1.0.0 copy "ui_guard: ^1.0.0" to clipboard
ui_guard: ^1.0.0 copied to clipboard

A simple and flexible role-based UI control plugin for Flutter.

UI Guard Package

Pub build Star on Github Flutter Website


Widgets that make role-based UI control simple and scalable. Built to keep your Flutter app secure and user-friendly.

*Note: All widgets in the ui_guard package work seamlessly with your role management logic.


πŸ” Why use ui_guard? #

In many apps, you need to control access to certain parts of your UI:

  • Show settings only to admins
  • Render upgrade buttons for guests
  • Show/hide widgets based on subscription level

ui_guard lets you do this easily and declaratively β€” using only Dart.


✨ Features #

  • βœ… Guard widgets or entire screens based on roles
  • πŸ”„ Easily update roles at runtime
  • πŸ“¦ Stateless and pure Dart β€” no native dependencies
  • πŸ§ͺ Testable and platform-agnostic
  • 🧩 Works with any state management

πŸ“¦ Installation #

Add this to your pubspec.yaml:

dependencies:
  ui_guard: ^1.0.0

🧠 Core API #

A simple class to store and manage the current user's roles.

πŸ”Ή Guard

A simple class to store and manage the current user's roles.

final guard = Guard();
guard.setUserRoles(['admin']); // Set roles for current user

print(guard.currentRoles); // ['admin']

πŸ”Ή AccessGuard

Renders content conditionally based on required roles.

AccessGuard(
  guard: guard,
  requiredRoles: ['admin'],
  builder: (_) => const Text('Admin Panel'),
  fallbackBuilder: (_) => const Text('Access Denied'),
);

πŸ”Ή RoleBasedView

Use when you want to show/hide a single widget inline.

AccessGuard(
  guard: guard,
  requiredRoles: ['admin'],
  builder: (_) => const Text('Admin Panel'),
  fallbackBuilder: (_) => const Text('Access Denied'),
);

πŸ”Ή RoleGuard

Utility class with common access logic:

RoleGuard.hasAnyRole(['admin'], ['admin', 'user']); // true
RoleGuard.hasAllRoles(['admin', 'editor'], ['admin']); // true

πŸ“± Example App #

Here’s a complete usage example. You can also explore the /example folder included with the package.

      import 'package:flutter/material.dart';
      import 'package:ui_guard/ui_guard.dart'; // Your plugin
      
      void main() {
        runApp(const RoleBasedApp());
      }
      
      class RoleBasedApp extends StatelessWidget {
        const RoleBasedApp({super.key});
      
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            title: 'UI Guard Plugin Example',
            theme: ThemeData(primarySwatch: Colors.deepPurple),
            home: const RoleHomePage(),
          );
        }
      }
      
      class RoleHomePage extends StatefulWidget {
        const RoleHomePage({super.key});
      
        @override
        State<RoleHomePage> createState() => _RoleHomePageState();
      }
      
      class _RoleHomePageState extends State<RoleHomePage> {
        final Guard guard = Guard();
      
        @override
        void initState() {
          super.initState();
          guard.setUserRoles(['admin']); // Default role
        }
      
        void _toggleRole() {
          final isAdmin = guard.currentRoles.contains('admin');
          final newRole = isAdmin ? 'guest' : 'admin';
          setState(() {
            guard.setUserRoles([newRole]);
          });
        }
      
        @override
        Widget build(BuildContext context) {
          final currentRole = guard.currentRoles.join(', ');
      
          return Scaffold(
            appBar: AppBar(title: const Text('Role-Based UI Example')),
            body: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Current Role: $currentRole',
                    style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(height: 30),
      
                  /// Show different content based on access
                  AccessGuard(
                    guard: guard,
                    requiredRoles: ['admin'],
                    builder: (_) => const AdminPanel(),
                    fallbackBuilder: (_) => const GuestMessage(),
                  ),
      
                  const SizedBox(height: 30),
                  ElevatedButton.icon(
                    onPressed: _toggleRole,
                    icon: const Icon(Icons.sync_alt),
                    label: Text(
                      guard.currentRoles.contains('admin')
                          ? 'Switch to Guest'
                          : 'Switch to Admin',
                    ),
                  ),
                ],
              ),
            ),
          );
        }
      }
      
      class AdminPanel extends StatelessWidget {
        const AdminPanel({super.key});
      
        @override
        Widget build(BuildContext context) {
          return Column(
            children: const [
              Icon(Icons.admin_panel_settings, size: 48, color: Colors.green),
              SizedBox(height: 10),
              Text(
                'Welcome, Admin!\nYou have full access to this section.',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16),
              ),
            ],
          );
        }
      }
      
      class GuestMessage extends StatelessWidget {
        const GuestMessage({super.key});
      
        @override
        Widget build(BuildContext context) {
          return Column(
            children: const [
              Icon(Icons.lock_outline, size: 48, color: Colors.redAccent),
              SizedBox(height: 10),
              Text(
                'Restricted Area.\nYou are viewing this as a guest.',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16, color: Colors.red),
              ),
            ],
          );
        }
      }

🧩 Use Cases #

Here are some common scenarios where ui_guard is useful:

Use Case Example
Admin-only screens requiredRoles: ['admin']
Feature restrictions Hide paid features from free users
Auth state UI Show "Login" or "Logout" buttons based on roles
Nested permissions Show moderator tools for ['moderator', 'admin'] roles
Read-only vs edit access Conditionally render buttons or fields
Subscription tiers Control access with ['free', 'premium', 'pro'] roles

πŸ’¬ Contributing #

Contributions are welcome!

To contribute:

  1. Fork the repository
  2. Create a new branch
  3. Commit your changes
  4. Submit a pull request

πŸ› οΈ Dart SDK Version #

This package requires Dart SDK version >=2.14.

Please ensure your Flutter and Dart versions meet this requirement.


πŸ‘€ Maintainers #

  • MD. TANVIRUL ISLAM
9
likes
0
points
40
downloads

Publisher

verified publishertanvirdev.com

Weekly Downloads

A simple and flexible role-based UI control plugin for Flutter.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter

More

Packages that depend on ui_guard