skip to Main Content

I followed the following tutorial on the official site for sqflite: https://pub.dev/packages/sqflite

But on this line

var databasesPath = await getDatabasesPath();

I get the following error:

Exception has occurred.
StateError (Bad state: databaseFactory not initialized
databaseFactory is only initialized when using sqflite. When using sqflite_common_ffi
You must call databaseFactory = databaseFactoryFfi; before using global openDatabase API
)

These are my dependencies:

dependecies:
  flutter:
    sdk: flutter
  sqflite: ^2.2.8
  path: ^1.8.2

I tried to open the Database without getting a path from getDatabasePath():

await openDatabase('demo.db', version: 1,...

But this throws the same error on openDatabase.

As I am not using sqflite_common_ffi I do not know what to do and would appreciate your help.

Edit:
I now also tried to use the complete example on the end of the page docs.flutter.dev/cookbook/persistence/sqlite. I think it is some kind of configuration error, because the same project works on another machine of mine.

2

Answers


  1. something I usually did is this way, hope this snap shot help you

      /// singleton pattern
      AppDataBase._internal() {
        // if (_database == null) database;
      }
      static final AppDataBase instance = AppDataBase._internal();
    
      /// sqflite datbase instance
      static Database? _database;
    
      /// gets database instance
      Future<Database> get database async {
        if (_database != null) return _database!;
        _database = await _initDB();
        return _database!;
      }
    
      /// initialize the database
      Future<Database> _initDB() async {
        print('createing databse');
        final dbPath = await getDatabasesPath();
        final path = join(dbPath, 'taskino.db');
        print('path is $path');
        return await openDatabase(path,
            version: 1, onCreate: _onCreate, onConfigure: _onConfigure);
      }
    
    

    then from the main I call my init to create db like this

    Future<void> main() async {
      await WidgetsFlutterBinding.ensureInitialized();
      await AppDataBase.instance.initDb();
      runApp(const MyApp());
    }
    
    

    I hope this helps you to could initialize your db

    Login or Signup to reply.
  2. dependencies:
       sqflite_common_ffi: any
    
    //in main.dart write this:
    import 'package:sqflite_common_ffi/sqflite_ffi.dart';
    Future main() async {
    
    // Initialize FFI
    sqfliteFfiInit();
    
    
     databaseFactory = databaseFactoryFfi;
     runApp(MyApp());
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search