Flutter sqflite:热重载后数据库不稳定 [英] Flutter sqflite: Database unstable after hot reload

查看:152
本文介绍了Flutter sqflite:热重载后数据库不稳定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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

以下是打开的功能

  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 

您可以看到数据库已打开( DB = 1161< db_name> .db true )
在执行查询之前的行上( await _db.query(...); )

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

如果您需要了解 _InitDBDataState 在做什么以了解错误的上下文,
您可以检查

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

推荐答案

sqflite通过查找打开的数据库(如果有的话)来支持热重启(即dart端重新启动,但本机数据库仍处于打开状态).热重装应该不会造成任何问题.

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.

我唯一能想到的就是您是否在某个地方调用了 _db.close().在典型的一个数据库方案中,您应该只在启动时打开数据库,而永远不要关闭它.

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.

如果您处于这种情况,可以确保从不调用close()吗?(并尝试注释此代码)

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

这篇关于Flutter sqflite:热重载后数据库不稳定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆