HOW TO DO COUNT USING DRIFT FLUTTER / MOOR (RENAMED)
14-Jun-2023 - Muthomi Kathurima
PROBLEM
I have a mobile application am building, with offline mode implemented using sqlite with help of Drift (simonbinder.eu). Persistence is key to usability in the modern mobile development field to ensure usability is not affected whether or not internet is available.
Because devices have no limited storage as before, we can afford to implement local DB and do sync when there is internet connection. Anyway, back to the problem, I needed to show statistics of the records in the DB emulating real time capabilities as records get into the DB. (Records are coming from Near Field Communication readings).
I used drift package and was looking for a way to watch the values, by using Stream and Stream Builder. Drift by default helps to implement this by using watch keyword, but the specifics on how to achieve count is not well documented. I implemented a solution after multiple attempts and here is the solution.
SOLUTION & THE CODE
Stream<int> getCount() {
final count = tableName.id.count(distinct: true);
final query = selectOnly(tableName)
..where(tableName.timestamp.contains('currentDate'));
query.addColumns([count]);
print(query.get().toString());
return query.map((row) => row.read(count)).watchSingle();
}
`tableName` is your table name. you can then set conditions in within the selectOnly query. you can also do the custom expression similar to one set called count
You can then use the StreamBuilder to get the values to your Widget.
Happy Coding!