How to count records in sqlite db table using moor_flutter package?

Issue

How do I count all rows in a table and get number of rows as a result using the moor_flutter package?

I have seen moor_flutter official documentation here but I can’t find what I’m looking for.

I was hoping it would be like the function below according to the similarities in crud functions when using the moor_flutter package but it is not working either.

Future<int<Person>> countPersons() => count(persons).get();

Solution

I figured out a way to find count of table rows. Here is a complete solution with basic comments,

//Create expression of count
var countExp = persons.id.count();

//Moor creates query from Expression so, they don't have value unless you execute it as query.  
//Following query will execute experssion on Table.
final query = selectOnly(persons)..addColumns([countExp]);
var result = await query.map((row) => row.read(countExp)).getSingle();

Please note that I have used selectOnly instead of select because I am not interested in any column except Count.

Answered By – Iducool

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *