5

When I try to create a data object to save in my database, it is giving me a warning saying that the id is required. However, the is should be automatically created by moor when added to the database, as it is marked as autoincrement. My table code is

class Countdowns extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text().withLength(min: 1, max: 100)();
  DateTimeColumn get date => dateTime()();
}

Is this warning safe to ignore? If not, what should I do about it? My code to create the data object is

countdown = Countdown(date: initialDate);

I will fill in the name field when the user enters a name for the countdown.

Nailuj29
  • 750
  • 1
  • 10
  • 28

1 Answers1

5

According to Moor documentation- Columns with a default value (either through autoIncrement or by using default), are still marked as @required in generated data classes. This is because they are meant to represent a full row, and every row will have those values. Use companions when representing partial rows, like for inserts or updates.

So you can use Companions for inserting/updating data. Companions are also auto-generated and you can use TableNameCompanion.insert() constructor to insert data.

You can read more on the official moor docs. https://moor.simonbinder.eu/docs/getting-started/advanced_dart_tables/

There is also an official issue on Moor github where the author explains the reason for having @required on autoincrement. https://github.com/simolus3/moor/issues/548

Zeeshan Hussain
  • 802
  • 6
  • 9
  • How could I turn a companion into a data class? – Nailuj29 Jul 29 '20 at 18:09
  • The generated class will have both the companion and the data class. Companion is only used for insertion. You will get the data class when you access the database values. Why do you want to convert a companion into a data class? – Zeeshan Hussain Jul 29 '20 at 18:13
  • My bloc takes a list of the data class as its state. I ended up just refactoring the code to re-query the database after each insert instead of adding it to the list. – Nailuj29 Jul 29 '20 at 18:14
  • I can't tell much without seeing the actual code. You don't need to re-query the database. moor provides us with streams. So just use streams and you won't need to re-query or add anything into the bloc. – Zeeshan Hussain Jul 29 '20 at 18:24
  • the code can be found [here](https://github.com/nailuj29gaming/flutter_countdown) – Nailuj29 Jul 29 '20 at 18:55
  • can you please provide an example of using streams? – Nailuj29 Jul 29 '20 at 22:05
  • @Nailuj29 you can read this article it covers streams and other stuffs https://resocoder.com/2019/06/26/moor-room-for-flutter-tables-queries-fluent-sqlite-database/ . – Zeeshan Hussain Jul 30 '20 at 12:20