davidmartos96 / sqflite_sqlcipher

SQLite flutter plugin
BSD 2-Clause "Simplified" License
96 stars 41 forks source link

Use SQLCipher with createDatabaseFactoryFfi: ffiInit asks a static function #48

Closed MobiliteDev closed 3 years ago

MobiliteDev commented 3 years ago

I'm trying to create a example with FFI compatible with iOS, Android, MacOS and Windows.

I followed this sample.

My Code

  sqflite_common_ffi: ^2.0.0+1
  sqlcipher_flutter_libs: ^0.5.0
  sqlcipher_library_windows: ^1.0.1
  sqlite3: ^1.1.2
late Database _db;

  /// Open SQLCipher lib
  DynamicLibrary _sqlcipherOpen() {
    if (Platform.isLinux || Platform.isAndroid) {
      return openCipherOnAndroid();
    }
    if (Platform.isIOS || Platform.isMacOS) {
      return DynamicLibrary.process();
    }
    if (Platform.isWindows) {
      return openSQLCipherOnWindows();
    }

    throw UnsupportedError('Unsupported platform: ${Platform.operatingSystem}');
  }

  ///Init pour SQLCipher
  void initApiForSQLiteWithSQLCipher() {
    open.overrideForAll(_sqlcipherOpen);
  }

  ///Create local DB with password 'test'
  Future createLocalDBWithSqlCipher() async {
    final DatabaseFactory dbFactory =
        createDatabaseFactoryFfi(ffiInit: initApiForSQLiteWithSQLCipher);

    _db = await dbFactory.openDatabase(
      Directory.current.path + "/db_pass_1234.db",
      options: OpenDatabaseOptions(
        version: 1,
        onConfigure: (db) async {
          // This is the part where we pass the "password"
          await db.rawQuery("PRAGMA KEY='1234'");
        },
        onCreate: (db, version) async {
          db.execute("CREATE TABLE t (i INTEGER)");
        },
      ),
    );
  }

I'm testing on Windows and I have this error

image

The fact is, if I set the void initApiForSQLiteWithSQLCipher() to static function like this static void initApiForSQLiteWithSQLCipher() it is working, is it normal ? What is the way to work with no static function for ffiInit param ?

davidmartos96 commented 3 years ago

That is normal. There is no way to work around that. That's how isolates work. You need to use either a global or a static function. Also, I think here you don't need to include sqlite3 in your dependencies because it is already a transitive dependency from sqflite_common_ffi. There is no harm on importing it, only watch out for the possible version conflict.

MobiliteDev commented 3 years ago

Thank you for your very quick answer