get_storage

repository·master·Indexed 18 days ago

https://github.com/jonataslaw/get_storage

A fast, lightweight, synchronous key-value storage solution for Flutter that provides immediate in-memory access with automatic background disk backups. It is designed for simple persistent state storage, caching HTTP requests, and replacing SharedPreferences, offering basic CRUD operations, listeners for storage changes, and support for multiple isolated storage containers.

Tokens
1.6K
Snippets
8
Records
9
Agent score
63%

What's inside get_storage

  1. What GetStorage is and when to use it

    master

    Concept

    GetStorage is a fast, ultra-lightweight, synchronous key-value storage that combines in-memory access with disk backup. It is designed for high-speed read/write operations where data is immediately available in memory after a write call.

    Use Cases

    • Storing simple Maps.
    • Caching HTTP requests.
    • Storing simple user information.
    • Simple persistent state storage.
    • Replacing SharedPreferences.

    Limitations

    • Not a database: It does not support indexing or complex querying. For those needs, use Hive or Sqflite.
    • Background Disk Writes: While memory updates are instant, disk backups happen in the background. If you must ensure a write is finished on disk before proceeding, use await box.write(). If you find yourself needing to await every operation, a database might be a better fit.
  2. Install and setup GetStorage

    master

    To use get_storage, add it to your pubspec.yaml dependencies and run flutter packages get. You must initialize the storage driver asynchronously in your main() function before running the app.

    dependencies:
      get_storage:
    main() async {
      await GetStorage.init();
      runApp(App());
    }
  3. Customize iOS Launch Screen Assets

    master

    To change the launch screen image for your iOS application, you can either replace the image files directly in the directory or use Xcode.

    Option 1: Direct File Replacement Replace the existing image files within the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory with your own assets.

    Option 2: Using Xcode

    1. Open your Flutter project's iOS workspace using the command: open ios/Runner.xcworkspace.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the launch images.
    open ios/Runner.xcworkspace
  4. Initialize GetStorage

    master

    Before using any storage operations, you must initialize the storage driver. It is critical to await the initialization to prevent side effects. You can specify a custom container name to isolate different sets of data.

    Use GetStorage.init() to start the storage drive.

    // Initialize the default 'GetStorage' container
    await GetStorage.init();
    
    // Or initialize a specific container
    await GetStorage.init('my_custom_container');
  5. Basic CRUD operations with GetStorage

    master

    You can interact with storage using a GetStorage instance. Use write to save data, read to retrieve it, remove to delete a specific key, and erase to clear the entire container. Data is written to memory instantly and backed up to disk in the background.

    final box = GetStorage();
    
    // Write
    box.write('quote', 'GetX is the best');
    
    // Read
    print(box.read('quote'));
    
    // Remove a key
    box.remove('quote');
    
    // Erase everything
    box.erase();
  6. Create and initialize multiple storage containers

    master

    You can create isolated storage containers by providing a unique name to the GetStorage constructor. If using a named container, you must initialize it specifically using GetStorage.init('name') before use.

    // Create a named container
    GetStorage g = GetStorage('MyStorage');
    
    // Initialize the specific container
    await GetStorage.init('MyStorage');
  7. Listen to storage changes

    master

    GetStorage allows you to subscribe to changes. You can listen to any change within a container using listen(), or listen to changes on a specific key using listenKey(). Always remember to dispose of your listeners to prevent memory leaks.

    // Listen to all changes in the box
    Function? disposeListen;
    disposeListen = box.listen(() {
      print('box changed');
    });
    
    // Dispose the listener when done
    disposeListen?.call();
    
    // Listen to a specific key
    box.listenKey('key', (value) {
      print('new key is $value');
    });
  8. Write and manage data in GetStorage

    master

    Use the following methods to persist data. Note that write and remove operations are asynchronous and involve a flushing mechanism to ensure data is saved to the underlying driver.

    • write(key, value): Writes a value to the specified key.
    • writeIfNull(key, value): Writes a value only if the key does not already exist.
    • remove(key): Deletes the data associated with the specified key.
    • erase(): Clears all data from the current container.
    • save(): Manually triggers a flush to save data.
    final storage = GetStorage('settings');
    
    // Write data
    await storage.write('theme', 'dark');
    
    // Write only if null
    await storage.writeIfNull('language', 'en');
    
    // Remove a specific key
    await storage.remove('theme');
    
    // Clear everything
    await storage.erase();
  9. Read and check data with GetStorage

    master

    Once initialized, you can access data using a GetStorage instance. You can read values by key, check if a key exists, or retrieve all keys and values.

    • read<T>(key): Retrieves the value associated with the key as type T.
    • hasData(key): Returns true if the value at the key is not null.
    • getKeys<T>(): Returns all keys in the container.
    • getValues<T>(): Returns all values in the container.
    final storage = GetStorage('my_container');
    
    // Read a value
    String? name = storage.read<String>('name');
    
    // Check if data exists
    if (storage.hasData('name')) {
      print('Name exists!');
    }
    
    // Get all keys
    List<String> keys = storage.getKeys<String>();