havin_generate_userid 1.0.2 copy "havin_generate_userid: ^1.0.2" to clipboard
havin_generate_userid: ^1.0.2 copied to clipboard

A Flutter plugin for generating and persisting unique random UUIDv4 User IDs securely on Android (EncryptedSharedPreferences / Auto-Backup) and iOS (Keychain).

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:havin_generate_userid/havin_generate_userid.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const UserIdExampleApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'User ID Generator Plugin',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const UserIdHomeScreen(),
    );
  }
}

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

  @override
  State<UserIdHomeScreen> createState() => _UserIdHomeScreenState();
}

class _UserIdHomeScreenState extends State<UserIdHomeScreen> {
  final HavinGenerateUserid _plugin = HavinGenerateUserid();
  final TextEditingController _customIdController = TextEditingController();

  String _platformVersion = 'Loading...';
  String _userId = 'Loading...';
  bool _isLoading = false;
  String? _statusMessage;

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

  @override
  void dispose() {
    _customIdController.dispose();
    super.dispose();
  }

  Future<void> _loadInitialData() async {
    setState(() {
      _isLoading = true;
    });

    String platformVersion;
    String userId;

    try {
      platformVersion = await _plugin.getPlatformVersion() ?? 'Unknown';
    } catch (e) {
      platformVersion = 'Error: $e';
    }

    try {
      userId = await _plugin.getUserId() ?? 'None';
    } catch (e) {
      userId = 'Error: $e';
    }

    if (!mounted) return;
    setState(() {
      _platformVersion = platformVersion;
      _userId = userId;
      _isLoading = false;
    });
  }

  Future<void> _fetchUserId() async {
    setState(() {
      _isLoading = true;
      _statusMessage = null;
    });

    try {
      final id = await _plugin.getUserId() ?? 'None';
      setState(() {
        _userId = id;
        _statusMessage = 'User ID fetched successfully';
      });
    } catch (e) {
      setState(() {
        _statusMessage = 'Failed to fetch User ID: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _regenerateUserId() async {
    setState(() {
      _isLoading = true;
      _statusMessage = null;
    });

    try {
      final newId = await _plugin.regenerateUserId() ?? 'None';
      setState(() {
        _userId = newId;
        _statusMessage = 'Regenerated new User ID successfully';
      });
    } catch (e) {
      setState(() {
        _statusMessage = 'Failed to regenerate: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _setCustomUserId() async {
    final customId = _customIdController.text.trim();
    if (customId.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please enter a custom User ID')),
      );
      return;
    }

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

    try {
      final success = await _plugin.setUserId(customId);
      if (success) {
        _customIdController.clear();
        final updatedId = await _plugin.getUserId() ?? customId;
        setState(() {
          _userId = updatedId;
          _statusMessage = 'Custom User ID saved successfully';
        });
      } else {
        setState(() {
          _statusMessage = 'Failed to save custom User ID';
        });
      }
    } catch (e) {
      setState(() {
        _statusMessage = 'Error setting User ID: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _clearUserId() async {
    setState(() {
      _isLoading = true;
      _statusMessage = null;
    });

    try {
      final success = await _plugin.clearUserId();
      if (success) {
        setState(() {
          _userId = 'Cleared';
          _statusMessage = 'User ID removed from secure storage';
        });
      } else {
        setState(() {
          _statusMessage = 'Failed to clear User ID';
        });
      }
    } catch (e) {
      setState(() {
        _statusMessage = 'Error clearing User ID: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _copyToClipboard() {
    Clipboard.setData(ClipboardData(text: _userId));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('User ID copied to clipboard')),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('User ID Plugin Demo'),
        centerTitle: true,
        elevation: 2,
      ),
      body: SafeArea(
        child: RefreshIndicator(
          onRefresh: _fetchUserId,
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Card(
                  elevation: 0,
                  color: theme.colorScheme.surfaceContainerHighest,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      children: [
                        Icon(Icons.info_outline, color: theme.colorScheme.primary),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            'Platform: $_platformVersion',
                            style: theme.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                Card(
                  elevation: 2,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Current User ID',
                          style: theme.textTheme.titleMedium?.copyWith(
                            color: theme.colorScheme.onSurfaceVariant,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 8),
                        SelectableText(
                          _userId,
                          style: theme.textTheme.titleLarge?.copyWith(
                            fontFamily: 'monospace',
                            fontWeight: FontWeight.bold,
                            color: theme.colorScheme.primary,
                          ),
                        ),
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            FilledButton.tonalIcon(
                              onPressed: _userId.isNotEmpty && _userId != 'Cleared' && _userId != 'Loading...'
                                  ? _copyToClipboard
                                  : null,
                              icon: const Icon(Icons.copy, size: 18),
                              label: const Text('Copy ID'),
                            ),
                            const Spacer(),
                            if (_isLoading)
                              const SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(strokeWidth: 2.5),
                              ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                if (_statusMessage != null) ...[
                  const SizedBox(height: 12),
                  Text(
                    _statusMessage!,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: _statusMessage!.startsWith('Error') || _statusMessage!.startsWith('Failed')
                          ? theme.colorScheme.error
                          : theme.colorScheme.primary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
                const SizedBox(height: 24),
                FilledButton.icon(
                  onPressed: _isLoading ? null : _fetchUserId,
                  icon: const Icon(Icons.refresh),
                  label: const Text('Get / Refresh User ID'),
                ),
                const SizedBox(height: 12),
                FilledButton.icon(
                  onPressed: _isLoading ? null : _regenerateUserId,
                  icon: const Icon(Icons.restart_alt),
                  label: const Text('Regenerate New UUID'),
                ),
                const SizedBox(height: 24),
                const Divider(),
                const SizedBox(height: 16),
                Text(
                  'Set Custom ID',
                  style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _customIdController,
                        decoration: const InputDecoration(
                          hintText: 'Enter custom User ID',
                          border: OutlineInputBorder(),
                          contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    FilledButton(
                      onPressed: _isLoading ? null : _setCustomUserId,
                      child: const Text('Set'),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                OutlinedButton.icon(
                  onPressed: _isLoading ? null : _clearUserId,
                  icon: const Icon(Icons.delete_outline, color: Colors.red),
                  label: const Text('Clear User ID from Storage', style: TextStyle(color: Colors.red)),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
0
likes
160
points
125
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for generating and persisting unique random UUIDv4 User IDs securely on Android (EncryptedSharedPreferences / Auto-Backup) and iOS (Keychain).

Repository (GitHub)
View/report issues

Topics

#user-id #device-id #keychain #security #uuid

License

MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on havin_generate_userid

Packages that implement havin_generate_userid