riverpod_sqflite 0.1.1 copy "riverpod_sqflite: ^0.1.1" to clipboard
riverpod_sqflite: ^0.1.1 copied to clipboard

An adapter to connect riverpod_sqflite with Riverpod.

Build Status codecov Star on Github License: MIT Discord

Deploys by Netlify

Riverpod


Say Hi to Riverpod_sqflite!

This is an official implementation of offline-persistence in Riverpod using Sqflite.

Usage #

First, you need to create a connector to the database. This can be done by creating a storageProvider:

final storageProvider = FutureProvider<JsonSqFliteStorage>((ref) async {
  // Initialize SQFlite. We should share the Storage instance between providers.
  return JsonSqFliteStorage.open(
    join(await getDatabasesPath(), 'riverpod.db'),
  );
});

Then, create a Notifier, mix-in Persistable and then invoke persist inside Notifier.build:

class TodosNotifier extends AsyncNotifier<List<Todo>>
    // We mix-in [Persistable] to enable the automatic persistence of the state.
    // Since the object will be encoded into JSON, we pass [String]/[String]
    // as key/value types.
    with
        Persistable<List<Todo>, String, String> {
  @override
  FutureOr<List<Todo>> build() async {
    // We call persist at the start of our `build` method.
    // This will:
    // - Read the DB and update the state with the persisted value the first
    //   time this method executes.
    // - Listen to changes on this provider and write those changes to the DB.
    // We "await" for persist to complete to make sure that the decoding is done
    // before we return the state.
    await persist(
      // A unique key for this state.
      // No other provider should use the same key.
      key: 'todos',
      // We pass our JsonSqFliteStorage instance. No need to "await" the Future.
      // Riverpod will take care of that.
      storage: ref.watch(storageProvider.future),
      // By default, state is cached offline only for 2 days.
      // In this example, we tell Riverpod to cache the state forever.
      options: const StorageOptions(cacheTime: StorageCacheTime.unsafe_forever),
      encode: jsonEncode,
      decode: (json) {
        final decoded = jsonDecode(json) as List;
        return decoded
            .map((e) => Todo.fromJson(e as Map<String, Object?>))
            .toList();
      },
    );

    // If a state is persisted, we return it. Otherwise we return an empty list.
    return state.value ?? [];
  }

  Future<void> add(Todo todo) async {
    // When modifying the state, no need for any extra logic to persist the change.
    // Riverpod will automatically cache the new state and write it to the DB.
    state = AsyncData([...await future, todo]);
  }
}
2
likes
150
points
218
downloads

Publisher

unverified uploader

Weekly Downloads

An adapter to connect riverpod_sqflite with Riverpod.

Documentation

API reference

License

MIT (license)

Dependencies

clock, collection, meta, riverpod, sqflite, test

More

Packages that depend on riverpod_sqflite