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

A singleton wrapper around SharedPreferences for managing authentication and session data with built-in error handling and debug logging.

flutter_data_shp_provider #

A singleton wrapper around SharedPreferences for managing authentication and session data with built-in error handling and debug logging.

Features #

  • Singleton Pattern: Ensures a single instance manages all SharedPreferences operations throughout your app lifecycle
  • Error Handling: All read/write operations are wrapped in try-catch blocks with graceful fallbacks
  • Debug Logging: Built-in logging that only prints in debug mode (kDebugMode)
  • Type Safety: All operations use string-based storage with clear APIs
  • Async Initialization: Explicit initialization pattern prevents race conditions
  • Convenient APIs: Both generic (getValue/saveValue) and specific getters/setters for common auth/session data

Getting Started #

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  flutter_data_shp_provider: ^0.0.1

Then run:

flutter pub get

Basic Usage #

1. Initialize the provider

Initialize the provider early in your app lifecycle, typically in main():

import 'package:flutter_data_shp_provider/flutter_data_shp_provider.dart';

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

  // Initialize SharedPreferences
  await DataShpProvider().initPrefs();

  runApp(MyApp());
}

2. Check initialization status

if (DataShpProvider().isInitialized) {
  // Safe to use
}

3. Use generic methods

// Save a value
await DataShpProvider().saveValue('myKey', 'myValue');

// Read a value
String value = DataShpProvider().getValue('myKey');

// Read with default value
String value = DataShpProvider().getValue('myKey', defaultValue: 'default');

4. Use specific auth/session getters and setters

// Save authentication data
await DataShpProvider().setToken('abc123token');
await DataShpProvider().setIdSesion('session-id-123');
await DataShpProvider().setKeyLogin('user@example.com');

// Read authentication data
String token = DataShpProvider().token;
String sessionId = DataShpProvider().idSesion;
String userLogin = DataShpProvider().keyLogin;

API Reference #

Initialization #

  • Future<void> initPrefs() - Initialize SharedPreferences (call before any other operations)
  • bool get isInitialized - Check if the provider has been initialized

Generic Methods #

  • String getValue(String key, {String defaultValue = ''}) - Read a value by key
  • Future<bool> saveValue(String key, String value) - Save a value by key

Authentication & Session Getters/Setters #

Getter Setter Description
keyLogin setKeyLogin(String) User login/email
passwordLogin setPasswordLogin(String) User password
idSesion setIdSesion(String) Session identifier
token setToken(String) Authentication token
validityInSeconds setValidityInSeconds(String) Token validity duration
idColeccionAuth setIdColeccionAuth(String) Auth collection ID
tipoUsuarioAuth setTipoUsuarioAuth(String) User type for auth
coleccionAuth setColeccionAuth(String) Auth collection name
idAppCliente setIdAppCliente(String) Client app identifier
offset setOffset(String) Time offset for sync

Utility Methods #

  • Future<bool> limpiarPreferencias() - Clear all preferences (use with caution)
  • static void logDebug(String message) - Log messages in debug mode only

Example #

See the example directory for a complete sample application.

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await DataShpProvider().initPrefs();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('DataShpProvider Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // Save user session
              await DataShpProvider().setToken('my-secure-token');
              await DataShpProvider().setIdSesion('session-123');

              // Read values
              print('Token: ${DataShpProvider().token}');
              print('Session: ${DataShpProvider().idSesion}');
            },
            child: Text('Save & Read Session'),
          ),
        ),
      ),
    );
  }
}

Error Handling #

All operations gracefully handle errors:

  • Uninitialized state: Returns default values or false for write operations
  • Read errors: Returns the specified defaultValue (or empty string)
  • Write errors: Returns false
  • All errors are logged in debug mode for troubleshooting

Additional Information #

Contributing #

Contributions are welcome! Please feel free to submit issues or pull requests.

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Support #

For issues, questions, or feature requests, please file an issue on the project repository.

0
likes
140
points
335
downloads

Publisher

unverified uploader

Weekly Downloads

A singleton wrapper around SharedPreferences for managing authentication and session data with built-in error handling and debug logging.

Documentation

API reference

License

MIT (license)

Dependencies

flutter, shared_preferences

More

Packages that depend on flutter_data_shp_provider