Flutter sqflite: Database unstable after hot reload

自作多情 提交于 2021-01-29 16:23:45

问题


I have the following code

  Future<InitData> getInitialData() async {
    print('OPENING');
    await open();
    print('DB = $_db ${_db.isOpen}');
    final rawDayActionTypes = await _db.query(...);

Where function open is the following

  Future<Database> open() async {
    if (_db != null && _db.isOpen) {
      return _db;
    }

    final dbPath = await sql.getDatabasesPath();
    final myDBPath = path.join(dbPath, db_name);
    _db = await sql.openDatabase(myDBPath, onCreate: _onCreateDB, version: 1);
    return _db;
  }

But after a hot reload, I get often the following error:

I/flutter (10806): DB = 1161 <db_name>.db true
E/flutter (10806): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(error database_closed)
E/flutter (10806): #0      SqfliteDatabaseMixin.checkNotClosed 
package:sqflite_common/src/database_mixin.dart:282
E/flutter (10806): #1      SqfliteDatabaseExecutorMixin._rawQuery 
package:sqflite_common/src/database_mixin.dart:125
E/flutter (10806): #2      SqfliteDatabaseExecutorMixin.query 
package:sqflite_common/src/database_mixin.dart:110
E/flutter (10806): #3      DBService.getInitialData 
package:productive_diary/db/db_service.dart:56
E/flutter (10806): <asynchronous suspension>
E/flutter (10806): #4      _InitDBDataState._fetchData 
package:productive_diary/initScreen.dart:53
E/flutter (10806): #5      _InitDBDataState.didChangeDependencies 

As you can see the DB was open (DB = 1161 <db_name>.db true)
on the line before executing the query(await _db.query(...);)

If you need to know what _InitDBDataState is doing in order to understand the context of the error,
you can check this related question


回答1:


sqflite supports hot-restart by finding the opened database if any (i.e. the dart side restarts but the native database is still open). hot-reload should not cause any issue.

The only thing I could think off is if you have a _db.close() call somewhere. In a typical one database scenario you should simply open the database on start and never close it.

If you are in this scenario, can ensure that close() is never called? (and try to comment this code)



来源:https://stackoverflow.com/questions/61599995/flutter-sqflite-database-unstable-after-hot-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!