Skip to main content

appforge_kit 0.0.1 copy "appforge_kit: ^0.0.1" to clipboard
appforge_kit: ^0.0.1 copied to clipboard

A production-ready foundation kit for Flutter apps featuring multi-environment management, auth gates, crash boundaries, and session guards.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:appforge_kit/appforge_kit.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 1. Initialize AppForge with environment & global crash handling
  await AppForge.init(
    environment: AppEnvironment.dev(
      baseUrl: 'https://dev.api.example.com',
      showBanner: true,
      extra: {'apiTimeout': 30000, 'supportEmail': 'support@example.com'},
    ),
    onCrash: (error, stack) {
      AppForgeLogger.e('Captured by AppForge onCrash callback', error: error);
    },
  );

  runApp(const AppForgeDemoApp());
}

class AppForgeDemoApp extends StatefulWidget {
  const AppForgeDemoApp({super.key});

  @override
  State<AppForgeDemoApp> createState() => _AppForgeDemoAppState();
}

class _AppForgeDemoAppState extends State<AppForgeDemoApp> {
  final AuthGateController _authController = AuthGateController();
  final InactivityController _inactivityController = InactivityController();
  bool _mockLoggedIn = false;

  @override
  Widget build(BuildContext context) {
    return AppInactivityDetector(
      controller: _inactivityController,
      // 15 seconds for easy demo testing (normally 5-10 minutes)
      timeoutDuration: const Duration(seconds: 15),
      onTimeout: () {
        AppForgeLogger.w('Inactivity timeout reached! Locking session...');
        showDialog(
          context: AppForge.navigatorKey.currentContext!,
          builder: (ctx) => AlertDialog(
            title: const Row(
              children: [
                Icon(Icons.lock_clock, color: Colors.amber),
                SizedBox(width: 8),
                Text('Session Timed Out'),
              ],
            ),
            content: const Text(
              'No user interaction was detected for 15 seconds. Please re-authenticate.',
            ),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(ctx);
                  setState(() => _mockLoggedIn = false);
                  _authController.setAuthenticated(false);
                },
                child: const Text('OK, Log In Again'),
              ),
            ],
          ),
        );
      },
      child: MaterialApp(
        title: 'AppForge Kit Demo',
        debugShowCheckedModeBanner: false,
        navigatorKey: AppForge.navigatorKey,
        builder: AppForge.builder(
          onBannerTap: () {
            ScaffoldMessenger.of(AppForge.navigatorKey.currentContext!)
                .showSnackBar(
              SnackBar(
                content: Text(
                  'Environment: ${AppForge.env.name} | BaseUrl: ${AppForge.baseUrl}',
                ),
                backgroundColor: AppForge.env.bannerColor,
              ),
            );
          },
        ),
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2563EB)),
          useMaterial3: true,
        ),
        home: AuthGate(
          controller: _authController,
          minSplashDuration: const Duration(milliseconds: 1500),
          isAuthenticated: () async {
            // Simulate checking token from secure storage
            await Future.delayed(const Duration(milliseconds: 500));
            return _mockLoggedIn;
          },
          splashScreen: const SplashScreenDemo(),
          loginScreen: LoginScreenDemo(
            onLoginSuccess: () {
              setState(() => _mockLoggedIn = true);
              _authController.setAuthenticated(true);
            },
          ),
          homeScreen: HomeScreenDemo(
            onLogout: () {
              setState(() => _mockLoggedIn = false);
              _authController.setAuthenticated(false);
            },
          ),
        ),
      ),
    );
  }
}

// ==================== Splash Screen ====================
class SplashScreenDemo extends StatelessWidget {
  const SplashScreenDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0F172A),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: const Color(0xFF2563EB),
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: const Color(0xFF2563EB).withOpacity(0.5),
                    blurRadius: 24,
                    offset: const Offset(0, 8),
                  ),
                ],
              ),
              child: const Icon(Icons.flash_on_rounded, size: 48, color: Colors.white),
            ),
            const SizedBox(height: 24),
            const Text(
              'AppForge Kit',
              style: TextStyle(
                color: Colors.white,
                fontSize: 28,
                fontWeight: FontWeight.bold,
                letterSpacing: 1.2,
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              'Checking environment and credentials...',
              style: TextStyle(color: Color(0xFF94A3B8), fontSize: 13),
            ),
            const SizedBox(height: 32),
            const SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(
                strokeWidth: 2.5,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF38BDF8)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// ==================== Login Screen ====================
class LoginScreenDemo extends StatelessWidget {
  final VoidCallback onLoginSuccess;

  const LoginScreenDemo({super.key, required this.onLoginSuccess});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AppForge Login Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.lock_person_outlined, size: 72, color: Color(0xFF2563EB)),
              const SizedBox(height: 16),
              const Text(
                'Welcome Back',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 8),
              const Text(
                'AuthGate automatically routed here because user token was empty.',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 32),
              ElevatedButton.icon(
                onPressed: onLoginSuccess,
                icon: const Icon(Icons.login),
                label: const Text('Log In with Mock Token'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF2563EB),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ==================== Home Screen ====================
class HomeScreenDemo extends StatefulWidget {
  final VoidCallback onLogout;

  const HomeScreenDemo({super.key, required this.onLogout});

  @override
  State<HomeScreenDemo> createState() => _HomeScreenDemoState();
}

class _HomeScreenDemoState extends State<HomeScreenDemo> {
  bool _triggerCrash = false;

  @override
  Widget build(BuildContext context) {
    if (_triggerCrash) {
      // Deliberately trigger an unhandled error to showcase AppCrashBoundary
      throw StateError('Simulated crash! AppCrashBoundary intercepted successfully.');
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('AppForge Kit Showcase'),
        actions: [
          IconButton(
            tooltip: 'Logout',
            icon: const Icon(Icons.logout),
            onPressed: widget.onLogout,
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16.0),
        children: [
          // Environment card
          Card(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: AppForge.env.bannerColor,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          AppForge.env.name,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8),
                      const Text(
                        'Active Environment',
                        style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Text('Base URL: ${AppForge.baseUrl}', style: const TextStyle(fontSize: 13)),
                  Text(
                    'Logging Enabled: ${AppForge.env.enableLogging}',
                    style: const TextStyle(fontSize: 13),
                  ),
                  Text(
                    'Show Banner: ${AppForge.env.showBanner}',
                    style: const TextStyle(fontSize: 13),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),

          // Action Demos
          Card(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            child: Column(
              children: [
                ListTile(
                  leading: const Icon(Icons.navigation, color: Colors.blue),
                  title: const Text('Context-Free Navigation'),
                  subtitle: const Text('Navigate via AppForgeNav.to(...) without context'),
                  trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                  onTap: () {
                    AppForgeNav.to(
                      Scaffold(
                        appBar: AppBar(title: const Text('Pushed Screen')),
                        body: Center(
                          child: ElevatedButton(
                            onPressed: () => AppForgeNav.back(),
                            child: const Text('AppForgeNav.back()'),
                          ),
                        ),
                      ),
                    );
                  },
                ),
                const Divider(height: 1),
                ListTile(
                  leading: const Icon(Icons.bug_report, color: Colors.red),
                  title: const Text('Test Crash Boundary'),
                  subtitle: const Text('Simulate a crash & view modern fallback screen'),
                  onTap: () {
                    setState(() => _triggerCrash = true);
                  },
                ),
                const Divider(height: 1),
                ListTile(
                  leading: const Icon(Icons.terminal, color: Colors.green),
                  title: const Text('Test AppForgeLogger'),
                  subtitle: const Text('Prints formatted emoji logs to console'),
                  onTap: () {
                    AppForgeLogger.d('This is a debug message');
                    AppForgeLogger.i('This is an informative message');
                    AppForgeLogger.w('This is a warning alert');
                    AppForgeLogger.e('This is an error event');
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Logs printed to debug console!')),
                    );
                  },
                ),
                const Divider(height: 1),
                ListTile(
                  leading: const Icon(Icons.timer_outlined, color: Colors.orange),
                  title: const Text('Inactivity Guard Active'),
                  subtitle: const Text('Do nothing for 15s to trigger timeout modal'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
2
likes
150
points
233
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A production-ready foundation kit for Flutter apps featuring multi-environment management, auth gates, crash boundaries, and session guards.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter

More

Packages that depend on appforge_kit