flutterdartflutter-moor

How to get the number of entries in a table using flutter_moor?


When I am adding an entry to the table, I need to know the number of elements in the table.

onPressed: () {
  final db = Provider.of<AppDb>(context);

  final habitCount = 0; /* Number of entries in the "Habits" table */
  db.into(db.habits)
    .insert(HabitsCompanion.insert(name: "Sleep", order: habitCount * 2 ));
},

How can I do this as easily as possible?


Solution

  • You can create DAO to manage all queries. Here I am giving you an example of todos table which is used in documentation.

    In this example, you can create a manual query by the queries key.

    @UseDao(tables: [Todos], queries: {'totalTodos': 'SELECT COUNT(*) FROM todos;'})
    class TodoDao extends DatabaseAccessor<MyDatabase> with _$TodoDaoMixin  {
    
      final MyDatabase database;
    
      TodoDao(this.database) : super(database);
    
      Future<int> getTotalRecords() {
        return totalTodos().getSingle();
      }
    }
    

    How to use:

    Selectable<int> total = TodoDao(database).totalTodos();
    total.getSingle().then((value) => print('Records: $value'));
    

    Hope you will understand the example. Do let me know if you have any questions.