Skip to content
Advertisement

How to stop class database file getting created multiple times when using flutter_moor?

Whenever I am adding a new row to my database in my flutter app, I am getting this error :

WARNING (moor): It looks like you’ve created the database classAppDatabase multiple times. When these two databases use the same QueryExecutor, race conditions will ocur and might corrupt the database.

I read different articles and deduced that I may have been calling the constructor more than once, but still not figuring out the way out of it.

Here are some code snippets for the initial reference:

pubspec.yaml:

moor_database.dart:

main.dart:

Although I am getting my Output fine and the app seems working, It is giving me an error in the debug console every time on hot-restarting :

The method ‘[]’ was called on null. Receiver: null Tried calling: ” (The actual error has a pair of square brackets followed by a pair of round brackets having a zero between the round brackets instead of quotes)

So, I want to get rid of both these errors so that I can start integrating my APIs

Thanks in advance!

Advertisement

Answer

You should not call AppDatabase() more than once in your application. Calling AppDatabase() creates a new instance every time and you end up with many instances of the database. The best way to do this is to create it once and provide it to the needed components. Also, check the Singleton pattern in Dart.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement