Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data does not update when I switch between databases #1117

Open
haidang750 opened this issue Jul 2, 2024 · 1 comment
Open

Data does not update when I switch between databases #1117

haidang750 opened this issue Jul 2, 2024 · 1 comment

Comments

@haidang750
Copy link

haidang750 commented Jul 2, 2024

I use floor package to auto generate sqflite database in my project. I tried to close the current database and used $FloorAppDatabase.databaseBuilder(dbPath).build() to switch to the new one but it kept the old data of the previous database.

Here is my code:

   @Database(version: 1, entities: [
     Customer,
     Product,
   ])
   abstract class AppDatabase extends FloorDatabase {
     AppDatabase();

     CustomerDao get customerDao;

     ProductDao get productDao;

     Future<void> deleteAllTables() async {
       await database.execute('DELETE FROM Customer');
       await database.execute('DELETE FROM Product');
     }
   }

   class DatabaseService {
     AppDatabase? _currentDatabase;
     CustomerDao? _customerDao;
     ProductDao? _productDao;

     Future<AppDatabase> _initDatabase(String dbPath) async {
       final database = await $FloorAppDatabase.databaseBuilder(dbPath).build();
       return database;
     }

     Future<void> switchDatabase(int? userId) async {
       // Close the current database if it exists
       await _closeCurrentDatabase();

       // Initialize the new database
       _currentDatabase =
           await _initDatabase('${userId?.toString() ?? AppConstants.APP_DATABASE_NAME}.db');
       _customerDao = _currentDatabase?.customerDao;
       _productDao = _currentDatabase?.productDao;
     }

     CustomerDao get customerDao => _customerDao!;
     ProductDao get productDao => _productDao!;

     Future<void> _closeCurrentDatabase() async {
       await _currentDatabase?.close();
       _currentDatabase = null;
     }
  }
@alextekartik
Copy link
Contributor

I'm not familiar with floor so I cannot say whether it is correct or not. Have you reported this issue in floor (https://github.com/pinchbv/floor) first?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants