Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "flutter: DatabaseException(open_failed...)"?

I'm trying to run my flutter app on my iPhone 7 but I'm receiving an error message. Running the app on my Android phone as well as on the iPhone XR simulator works fine. I also tried to test the app on my iPad and I got the exact same error message as shown below. Replacing the ios folder with a fresh copy did not solve the issue.

I've tried to run the latest sqflite version and flutter doctor shows no issues.

Future<Database> initDatabase() async {
    //Get the dir
    Directory directory = await getApplicationDocumentsDirectory();
    String path = directory.path + 'posts.db';

    //Open or Create the database using given path
    var postsDataBase = openDatabase(path, version: 1, onCreate: _createDb);
    return postsDataBase;
  }

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: DatabaseException(open_failed /var/mobile/Containers/Data/Application/04C0A23F-6C36-42C2-9CE5-C7C5370F59FA/Documentsposts.db)
#0      wrapDatabaseException 
package:sqflite/src/exception_impl.dart:11
<asynchronous suspension>
#1      SqfliteDatabaseFactoryImpl.wrapDatabaseException 
package:sqflite/src/factory_impl.dart:29
#2      SqfliteDatabaseMixin.safeInvokeMethod 
package:sqflite/src/database_mixin.dart:184
#3      SqfliteDatabaseMixin.openDatabase 
package:sqflite/src/database_mixin.dart:519
<asynchronous suspension>
#4      SqfliteDatabaseMixin.doOpen 
package:sqflite/src/database_mixin.dart:612
<asynchronous suspension>
#5      SqfliteDatabaseOpenHelper.openDatabase 
package:sqflite/src/database.dart:32
<asynchronous suspension>
#6      SqfliteDatabaseFactoryMixin.openDatabase.<anonymous closure> 
package:sqflite/src/factory_mixin.dart:100
<asynchronous suspension>
#7      ReentrantLock.synchronized.<anonymous closure>.<anonymous closure> 
package:synchronized/src/reentrant_lock.dart:33
#8      _rootRun  (dart:async/zone.dart:1124:13)
like image 436
Andreas Blum Avatar asked Sep 17 '25 07:09

Andreas Blum


2 Answers

Using db helper like this fixed my issue:


  Future<String> checkPath(String dbName) async {
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, dbName);
    if (await Directory(dirname(path)).exists()) {
    } else {
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (e) {
        print(e);
      }
    }
    return path;
  }

  initDB() async {
    String path = await checkPath(dbName);

    return await openDatabase(
      (path),
      onCreate: (db, version) {
    ...
    ...

like image 121
Emin Bilgiç Avatar answered Sep 19 '25 19:09

Emin Bilgiç


This worked for me.

String path = directory.path + '/' + 'posts.db';
like image 35
Jonathan Perez Avatar answered Sep 19 '25 20:09

Jonathan Perez