local_storage_manager 1.0.3 copy "local_storage_manager: ^1.0.3" to clipboard
local_storage_manager: ^1.0.3 copied to clipboard

A comprehensive Flutter local storage manager package for your app.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_shared_utilities/flutter_shared_utilities.dart';
import 'package:local_storage_manager/local_storage_manager.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Local Storage Manager Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF2196F3),
          brightness: Brightness.light,
        ),
        useMaterial3: true,
        appBarTheme: const AppBarTheme(centerTitle: true, elevation: 0),
        cardTheme: const CardThemeData(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF2196F3),
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
        appBarTheme: const AppBarTheme(centerTitle: true, elevation: 0),
        cardTheme: const CardThemeData(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ),
      home: const StorageExampleHomePage(),
    );
  }
}

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

  @override
  State<StorageExampleHomePage> createState() => _StorageExampleHomePageState();
}

class _StorageExampleHomePageState extends State<StorageExampleHomePage> {
  late final SharedPreferencesStorageManager _storageManager;

  bool _isInitialized = false;
  String _statusMessage = 'Initializing storage...';
  final List<String> _operationLogs = <String>[];

  // Demo data
  final Map<String, Object?> _demoUserProfile = <String, Object?>{
    'id': '12345',
    'name': 'John Doe',
    'email': 'john.doe@example.com',
    'age': 28,
    'isActive': true,
    'preferences': <String, Object?>{
      'theme': 'dark',
      'notifications': true,
      'language': 'en',
    },
    'tags': <String>['flutter', 'developer', 'mobile'],
    'lastLogin': DateTime.now().toIso8601String(),
  };

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

  Future<void> _initializeStorage() async {
    try {
      _storageManager = await SharedPreferencesStorageManager.create();
      if (mounted) {
        setState(() {
          _isInitialized = true;
          _statusMessage = 'Storage initialized successfully';
        });
        _addLog('βœ… Storage manager initialized');
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _statusMessage = 'Failed to initialize storage: $e';
        });
        _addLog('❌ Storage initialization failed: $e');
      }
    }
  }

  void _addLog(String message) {
    setState(() {
      _operationLogs.insert(0, '${DateTime.now().toIso8601String()}: $message');
      if (_operationLogs.length > 20) {
        _operationLogs.removeRange(20, _operationLogs.length);
      }
    });
  }

  Future<void> _demonstrateBasicOperations() async {
    if (!_isInitialized) return;

    _addLog('πŸ”„ Starting basic operations demo...');

    try {
      // String operation
      final stringResult = await _storageManager.setValue<String>(
        'demo_string',
        'Hello Local Storage Manager!',
      );
      stringResult.fold(
        (failure) => _addLog('❌ String save failed: ${failure.message}'),
        (success) => _addLog('βœ… String saved successfully'),
      );

      // Integer operation
      final intResult = await _storageManager.setValue<int>('demo_number', 42);
      intResult.fold(
        (failure) => _addLog('❌ Number save failed: ${failure.message}'),
        (success) => _addLog('βœ… Number saved successfully'),
      );

      // Boolean operation
      final boolResult = await _storageManager.setValue<bool>(
        'demo_boolean',
        true,
      );
      boolResult.fold(
        (failure) => _addLog('❌ Boolean save failed: ${failure.message}'),
        (success) => _addLog('βœ… Boolean saved successfully'),
      );

      // List operation
      final listResult = await _storageManager.setValue<List<String>>(
        'demo_list',
        <String>['apple', 'banana', 'cherry'],
      );
      listResult.fold(
        (failure) => _addLog('❌ List save failed: ${failure.message}'),
        (success) => _addLog('βœ… List saved successfully'),
      );

      // Retrieve and display values
      _retrieveAndDisplayValues();
    } catch (e) {
      _addLog('❌ Basic operations failed: $e');
    }
  }

  Future<void> _demonstrateComplexOperations() async {
    if (!_isInitialized) return;

    _addLog('πŸ”„ Starting complex operations demo...');

    try {
      // Store complex object
      final userResult = await _storageManager.setValue<Map<String, Object?>>(
        'user_profile',
        _demoUserProfile,
      );

      userResult.fold(
        (failure) => _addLog('❌ User profile save failed: ${failure.message}'),
        (success) => _addLog('βœ… User profile saved successfully'),
      );

      // Batch operations
      final batchData = <String, Object?>{
        'session_id': 'sess_${DateTime.now().millisecondsSinceEpoch}',
        'app_version': '1.0.0',
        'install_date': DateTime.now().toIso8601String(),
        'feature_flags': <String, bool>{
          'dark_mode': true,
          'push_notifications': false,
          'analytics': true,
        },
      };

      final batchResult = await _storageManager.setMultipleValues(batchData);
      batchResult.fold(
        (failure) => _addLog('❌ Batch save failed: ${failure.message}'),
        (success) => _addLog('βœ… Batch data saved successfully'),
      );

      // Retrieve complex data
      _retrieveComplexData();
    } catch (e) {
      _addLog('❌ Complex operations failed: $e');
    }
  }

  void _retrieveAndDisplayValues() {
    // Retrieve basic values with safe defaults
    final stringValue = _storageManager.getValueWithDefault<String>(
      'demo_string',
      defaultValue: 'Not found',
    );

    final numberValue = _storageManager.getValueWithDefault<int>(
      'demo_number',
      defaultValue: 0,
    );

    final boolValue = _storageManager.getValueWithDefault<bool>(
      'demo_boolean',
      defaultValue: false,
    );

    final listValue = _storageManager.getValueWithDefault<List<String>>(
      'demo_list',
      defaultValue: <String>[],
    );

    _addLog('πŸ“– Retrieved string: "$stringValue"');
    _addLog('πŸ“– Retrieved number: $numberValue');
    _addLog('πŸ“– Retrieved boolean: $boolValue');
    _addLog('πŸ“– Retrieved list: ${listValue.join(", ")}');
  }

  void _retrieveComplexData() {
    final userProfileResult = _storageManager.getValue<Map<String, Object?>>(
      'user_profile',
    );

    userProfileResult.fold(
      (failure) =>
          _addLog('❌ User profile retrieval failed: ${failure.message}'),
      (profile) {
        if (profile != null) {
          final name = profile.parse<String>('name');
          final email = profile.parse<String>('email');
          final age = profile.parse<int>('age');
          final isActive = profile.parse<bool>('isActive');
          final preferences = profile.parse<Map<String, Object?>>(
            'preferences',
          );

          _addLog('πŸ‘€ User: $name ($email)');
          _addLog('πŸ‘€ Age: $age, Active: $isActive');

          // Safely parse nested preferences
          if (preferences?.isNotEmpty == true) {
            final theme = preferences!.parse<String>('theme');
            final notifications = preferences.parse<bool>('notifications');
            _addLog('βš™οΈ Theme: $theme, Notifications: $notifications');
          }

          // Safely parse list of tags
          final tags = profile.parse<List<String>>('tags');
          if (tags?.isNotEmpty == true) {
            _addLog('🏷️ Tags: ${tags!.join(", ")}');
          }
        }
      },
    );
  }

  Future<void> _demonstrateStorageInfo() async {
    if (!_isInitialized) return;

    _addLog('πŸ“Š Getting storage information...');

    // Get all keys
    final keysResult = _storageManager.getAllKeys();
    keysResult.fold(
      (failure) => _addLog('❌ Failed to get keys: ${failure.message}'),
      (keys) => _addLog('πŸ”‘ Total keys: ${keys.length}'),
    );

    // Get storage size
    final sizeResult = _storageManager.getStorageSize();
    sizeResult.fold(
      (failure) => _addLog('❌ Failed to get size: ${failure.message}'),
      (size) => _addLog('πŸ“ Storage size: $size items'),
    );

    // Check if storage is empty
    final emptyResult = _storageManager.isEmpty();
    emptyResult.fold(
      (failure) => _addLog('❌ Failed to check empty: ${failure.message}'),
      (isEmpty) => _addLog('πŸ“¦ Storage empty: $isEmpty'),
    );
  }

  Future<void> _clearAllStorage() async {
    if (!_isInitialized) return;

    final result = await _storageManager.clearAll();
    result.fold((failure) => _addLog('❌ Clear failed: ${failure.message}'), (
      success,
    ) {
      _addLog('🧹 All storage cleared successfully');
      setState(() {
        _operationLogs.clear();
      });
    });
  }

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('Local Storage Manager Example'),
        backgroundColor: theme.colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Status Card
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Status',
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Icon(
                          _isInitialized
                              ? Icons.check_circle
                              : Icons.hourglass_empty,
                          color: _isInitialized ? Colors.green : Colors.orange,
                          size: 20,
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            _statusMessage,
                            style: theme.textTheme.bodyMedium,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // Operation Buttons
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _isInitialized
                      ? _demonstrateBasicOperations
                      : null,
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('Basic Operations'),
                ),
                ElevatedButton.icon(
                  onPressed: _isInitialized
                      ? _demonstrateComplexOperations
                      : null,
                  icon: const Icon(Icons.settings),
                  label: const Text('Complex Data'),
                ),
                ElevatedButton.icon(
                  onPressed: _isInitialized ? _demonstrateStorageInfo : null,
                  icon: const Icon(Icons.info),
                  label: const Text('Storage Info'),
                ),
                ElevatedButton.icon(
                  onPressed: _isInitialized ? _clearAllStorage : null,
                  icon: const Icon(Icons.clear_all),
                  label: const Text('Clear All'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: theme.colorScheme.error,
                    foregroundColor: theme.colorScheme.onError,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Logs Section
            Text(
              'Operation Logs',
              style: theme.textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),

            const SizedBox(height: 8),

            Expanded(
              child: Card(
                child: _operationLogs.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.history,
                              size: 48,
                              color: theme.colorScheme.onSurface.withValues(
                                alpha: 0.5,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              'No operations yet',
                              style: theme.textTheme.bodyLarge?.copyWith(
                                color: theme.colorScheme.onSurface.withValues(
                                  alpha: 0.5,
                                ),
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              'Tap a button above to see logs',
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: theme.colorScheme.onSurface.withValues(
                                  alpha: 0.5,
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    : ListView.builder(
                        padding: const EdgeInsets.all(8),
                        itemCount: _operationLogs.length,
                        itemBuilder: (context, index) {
                          final log = _operationLogs[index];
                          final parts = log.split(': ');
                          final timestamp = parts.isNotEmpty ? parts[0] : '';
                          final message = parts.length > 1
                              ? parts.sublist(1).join(': ')
                              : log;

                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 2),
                            child: RichText(
                              text: TextSpan(
                                style: theme.textTheme.bodySmall?.copyWith(
                                  fontFamily: 'monospace',
                                ),
                                children: [
                                  TextSpan(
                                    text:
                                        '${DateTime.tryParse(timestamp)?.toLocal().toString().substring(11, 19) ?? ''} ',
                                    style: TextStyle(
                                      color: theme.colorScheme.onSurface
                                          .withValues(alpha: 0.6),
                                    ),
                                  ),
                                  TextSpan(
                                    text: message,
                                    style: TextStyle(
                                      color: theme.colorScheme.onSurface,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
160
points
64
downloads

Publisher

unverified uploader

Weekly Downloads

A comprehensive Flutter local storage manager package for your app.

Repository (GitHub)
View/report issues

Topics

#local-storage #shared-preferences #hive #sqflite #cache

Documentation

API reference

License

MIT (license)

Dependencies

flutter, flutter_shared_utilities, shared_preferences

More

Packages that depend on local_storage_manager