Search code examples
databaseflutterdartnosqlsembast

NoSQL creating and accessing different store references


I am trying to create a NoSQL database for a Flutter app that has different stores for different activities done throughout the day (sleep, exercise, eating, etc.). I don't want to hard code the stores and want to be able to add and delete stores as needed.

The issue I'm encountering is the intMapStoreFactory.store() requires a static input but the inputs for SembastActivityRepository cannot be static. Is there a way to create and access custom store names from outside this WembastActivityRepository class?

Thank you!

import 'package:get_it/get_it.dart';
import 'package:sembast/sembast.dart';

import './activity.dart';
import './activity_repository.dart';

class SembastActivityRepository extends ActivityRepository {
  final activityName;
  SembastActivityRepository({this.activityName});
  
  final Database _database = GetIt.I.get();
  final StoreRef _store = intMapStoreFactory.store(activityName);

  @override
  Future<int> insertActivity(Activity activity) async {
    return await _store.add(_database, activity.toMap());
  }

  @override
  Future updateActivity(Activity activity) async {
    await _store.record(activity.id).update(_database, activity.toMap());
  }

  @override
  Future deleteActivity(int activityId) async {
    await _store.record(activityId).delete(_database);
  }

  @override
  Future<List<Activity>> getAllActivities() async {
    final snapshots = await _store.find(_database);
    return snapshots
        .map((snapshot) => Activity.fromMap(snapshot.key, snapshot.value))
        .toList(growable: false);
  }
}


Solution

  • I'm not sure what you mean by static but anyway your code could not compile and I strongly suggest using Strong mode to get compile time recommendation. A StoreRef is just a declaration of a store and its key and value type, you can create/and re-created a StoreRef at any time, the store itself is only created when you add records to it.

    If it is just to to get your code to compile, initialize _store in the constructor:

    class SembastActivityRepository {
      final String activityName;
      final StoreRef<int, Map<String, dynamic>> _store;
    
      SembastActivityRepository({this.activityName})
          : _store = intMapStoreFactory.store(activityName);
    
      // ...
    }