Skip to main content

klujo_flutter 0.0.4 copy "klujo_flutter: ^0.0.4" to clipboard
klujo_flutter: ^0.0.4 copied to clipboard

Engage your audience with interactive word games that capture attention, drive retention, and deliver real growth.

example/lib/main.dart

// Klujo Flutter SDK - Example Application
//
// This example demonstrates how to integrate the Klujo SDK into a Flutter app.
// It shows the complete flow:
//   1. SDK initialization with API key
//   2. Player authentication with email and name
//   3. Displaying games with the KlujoGame component
//   4. Adding the rewards floating button with KlujoRewards
//
// For more information, see the SDK documentation:
// https://klujo.com/docs/sdk/flutter

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

void main() {
  runApp(const KlujoExampleApp());
}

class KlujoExampleApp extends StatelessWidget {
  const KlujoExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Klujo Flutter Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6366F1)),
        useMaterial3: true,
      ),
      home: const KlujoExample(),
    );
  }
}

// ============================================================================
// CONFIGURATION
// ============================================================================
// Replace these values with your own credentials from the Klujo Dashboard
class KlujoConfig {
  // Your Klujo API key (required)
  // Get this from: https://app.klujo.com
  static const String apiKey = 'YOUR_API_KEY_HERE';

  // Optional: Your internal user ID to link Klujo players with your users
  // This helps you identify players in your own system
  static const String externalId = 'your-internal-user-id';

  // Environment: production or development
  // Use development for testing, production for live apps
  static const Environment environment = Environment.development;
}

// ============================================================================
// TYPES
// ============================================================================
enum Screen { loading, login, home }

// ============================================================================
// MAIN EXAMPLE WIDGET
// ============================================================================
class KlujoExample extends StatefulWidget {
  const KlujoExample({super.key});

  @override
  State<KlujoExample> createState() => _KlujoExampleState();
}

class _KlujoExampleState extends State<KlujoExample> {
  // ---------------------------------------------------------------------------
  // State Management
  // ---------------------------------------------------------------------------
  Screen _currentScreen = Screen.loading;
  final _emailController = TextEditingController();
  final _fullNameController = TextEditingController();
  bool _isLoading = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    _initializeSDK();
  }

  @override
  void dispose() {
    _emailController.dispose();
    _fullNameController.dispose();
    super.dispose();
  }

  // ---------------------------------------------------------------------------
  // SDK Initialization
  // ---------------------------------------------------------------------------
  /// Initialize the SDK when the app starts.
  /// This should be done ONCE, typically in your root component.
  Future<void> _initializeSDK() async {
    try {
      // KlujoSDK().initialization() sets up the SDK and creates/restores a player session.
      //
      // Parameters:
      //   - apiKey (required): Your Klujo API key
      //   - playerUUID (optional): Pass an existing UUID to restore a session,
      //     or null to create a new player
      //   - externalId (optional): Your internal user ID for cross-reference
      //   - environment (optional): Environment.production or Environment.development
      //
      // Returns: The player's UUID (save this to restore sessions later)
      final sdk = KlujoSDK();
      final playerUUID = await sdk.initialization(
        apiKey: KlujoConfig.apiKey,
        externalId: KlujoConfig.externalId,
        environment: KlujoConfig.environment,
      );

      debugPrint('[Klujo] SDK initialized successfully');
      debugPrint('[Klujo] Player UUID: $playerUUID');

      // Move to login screen after successful initialization
      setState(() => _currentScreen = Screen.login);
    } catch (e) {
      // Handle initialization errors (invalid API key, network issues, etc.)
      debugPrint('[Klujo] Initialization failed: $e');
      setState(() {
        _error = 'SDK initialization failed: $e';
        _currentScreen = Screen.login;
      });
    }
  }

  // ---------------------------------------------------------------------------
  // Player Authentication
  // ---------------------------------------------------------------------------
  /// Authenticate the player with their profile information.
  /// This links the anonymous player session to a user identity.
  Future<void> _handleLogin() async {
    final email = _emailController.text.trim();
    final fullName = _fullNameController.text.trim();

    // Validate input
    if (email.isEmpty && fullName.isEmpty) {
      setState(() => _error = 'Please enter at least your email or name');
      return;
    }

    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      // KlujoSDK().authentication() updates the player's profile information.
      //
      // Parameters:
      //   - email (optional): Player's email address
      //   - fullName (optional): Player's display name
      //
      // Returns: The player's UUID
      //
      // Note: At least one parameter should be provided.
      // Call this after your own login/registration flow completes.
      final sdk = KlujoSDK();
      final playerUUID = await sdk.authentication(
        email: email.isNotEmpty ? email : null,
        fullName: fullName.isNotEmpty ? fullName : null,
      );

      debugPrint('[Klujo] Player authenticated successfully');
      debugPrint('[Klujo] Player UUID: $playerUUID');

      // Navigate to home screen with game and rewards
      setState(() => _currentScreen = Screen.home);
    } catch (e) {
      debugPrint('[Klujo] Authentication failed: $e');
      setState(() => _error = 'Authentication failed: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // ---------------------------------------------------------------------------
  // Skip Authentication (Guest Mode)
  // ---------------------------------------------------------------------------
  /// Allow users to skip authentication and play as a guest.
  /// The SDK already created an anonymous player during initialization.
  void _handleSkipLogin() {
    debugPrint('[Klujo] Continuing as guest (anonymous player)');
    setState(() => _currentScreen = Screen.home);
  }

  // ---------------------------------------------------------------------------
  // Screen Rendering
  // ---------------------------------------------------------------------------

  /// Loading Screen - Shown while SDK initializes
  Widget _buildLoadingScreen() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Color(0xFF6366F1)),
          SizedBox(height: 16),
          Text(
            'Initializing Klujo SDK...',
            style: TextStyle(fontSize: 16, color: Color(0xFF6B7280)),
          ),
        ],
      ),
    );
  }

  /// Login Screen - User authentication form
  Widget _buildLoginScreen() {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(32),
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 400),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'Welcome',
                style: TextStyle(
                  fontSize: 32,
                  fontWeight: FontWeight.w700,
                  color: Color(0xFF111827),
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                'Sign in to track your progress and earn rewards',
                style: TextStyle(fontSize: 16, color: Color(0xFF6B7280)),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 32),

              // Error message display
              if (_error != null) ...[
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFEE2E2),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    _error!,
                    style: const TextStyle(
                      color: Color(0xFFDC2626),
                      fontSize: 14,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                const SizedBox(height: 16),
              ],

              // Full Name Input
              TextField(
                controller: _fullNameController,
                decoration: InputDecoration(
                  hintText: 'Full Name',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: const BorderSide(color: Color(0xFFD1D5DB)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: const BorderSide(color: Color(0xFFD1D5DB)),
                  ),
                ),
                textCapitalization: TextCapitalization.words,
                enabled: !_isLoading,
              ),
              const SizedBox(height: 16),

              // Email Input
              TextField(
                controller: _emailController,
                decoration: InputDecoration(
                  hintText: 'Email',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: const BorderSide(color: Color(0xFFD1D5DB)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                    borderSide: const BorderSide(color: Color(0xFFD1D5DB)),
                  ),
                ),
                keyboardType: TextInputType.emailAddress,
                enabled: !_isLoading,
              ),
              const SizedBox(height: 24),

              // Login Button
              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton(
                  onPressed: _isLoading ? null : _handleLogin,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF6366F1),
                    disabledBackgroundColor: const Color(0xFFA5B4FC),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: _isLoading
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Colors.white,
                          ),
                        )
                      : const Text(
                          'Continue',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                ),
              ),
              const SizedBox(height: 16),

              // Skip/Guest Option
              TextButton(
                onPressed: _isLoading ? null : _handleSkipLogin,
                child: const Text(
                  'Skip for now',
                  style: TextStyle(color: Color(0xFF6B7280), fontSize: 14),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Home Screen - Game display with rewards button
  Widget _buildHomeScreen() {
    return Stack(
      children: [
        // =================================================================== //
        // KLUJO GAME COMPONENT                                                //
        // =================================================================== //
        // KlujoGame renders a WebView with Klujo games.                       //
        //                                                                     //
        // Props:                                                              //
        //   - style (BoxDecoration): Custom container styles                  //
        //   - showLoading (bool): Show loading indicator (default: true)      //
        //   - showRewards (bool): Show in-game rewards UI (default: true)     //
        //                                                                     //
        // The component automatically uses the authenticated player's token.  //
        const Positioned.fill(child: KlujoGame(showLoading: true)),

        // =================================================================== //
        // KLUJO REWARDS COMPONENT                                             //
        // =================================================================== //
        // KlujoRewards displays a floating action button that opens a modal   //
        // showing the player's rewards.                                       //
        //                                                                     //
        // Props:                                                              //
        //   - position: KlujoRewardsPosition.bottomLeft | bottomRight |       //
        //               topLeft | topRight (default: bottomLeft)              //
        //   - compressed: bool - When true, shows only the icon.              //
        //                 When false, shows icon + text (default: true)       //
        //                                                                     //
        // The button appearance (color, text, icon) is configured in your     //
        // Klujo Dashboard settings.                                           //
        const KlujoRewards(
          position: KlujoRewardsPosition.bottomRight,
          compressed: false,
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      body: SafeArea(
        child: switch (_currentScreen) {
          Screen.loading => _buildLoadingScreen(),
          Screen.login => _buildLoginScreen(),
          Screen.home => _buildHomeScreen(),
        },
      ),
    );
  }
}
0
likes
140
points
20
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Engage your audience with interactive word games that capture attention, drive retention, and deliver real growth.

Homepage
Repository

License

unknown (license)

Dependencies

flutter, http, shared_preferences, url_launcher, webview_flutter

More

Packages that depend on klujo_flutter