I am trying to write a generic cache utility using sembast
. Follwoing is the code:
import 'package:sembast/sembast.dart';
import 'package:tachyon/core/domain/trait/map_serializer.dart';
class CachingController<T> {
final Database _cache;
final StoreRef<String, Map<String, dynamic>> _store =
stringMapStoreFactory.store('objects');
CachingController(this._cache);
Future<void> insertObjects(
MapSerializer mapSerializer, List<T> objectList) async {
final objectMap =
objectList.map((object) => mapSerializer.toMap(object)).toList();
await _store.addAll(_cache, objectMap);
}
Future<List<T>> getObjects(MapSerializer mapSerializer) async {
final finder = Finder(sortOrders: [SortOrder('phone_number')]);
final records = await _store.find(_cache, finder: finder);
final objectList =
records.map((record) => mapSerializer.fromMap(record.value)).toList();
return Future.value(objectList);
}
}
The abstract MapSerializer
class is:
abstract class MapSerializer<T> {
Map<String, dynamic> toMap(T item);
T fromMap(Map<String, dynamic> json);
}
But in the getObjects
method of CachingController<T>
I am getting this compiler error at the return statement.
The argument type 'List<dynamic>' can't be assigned to the parameter type 'FutureOr<List<T>>?'.
which goes away if I change the return statement to return Future.value(objectList as FutureOr<List<T>>?);
by adding casting but it doesn't seem to the correct way to do it.
I would love to have suggestion on what should be done here.
Future<List<T>> getObjects(MapSerializer<T> mapSerializer) async {
final finder = Finder(sortOrders: [SortOrder('phone_number')]);
final records = await _store.find(_cache, finder: finder);
final objectList =
records.map((record) => mapSerializer.fromMap(record.value)).toList();
return Future.value(objectList);
}
can you add T
in the function argument MapSerializer<T> mapSerializer
like this?