0

I'm trying init mysql db file in flutter. I'm using this code:

  static Future<void> initdb() async {
    final databasePath = await getDatabasesPath();
    final path = join(databasePath, 'models.db');
    _database = await openDatabase(path, version: 1, onCreate: (db, version) {
      return db.execute(
        'CREATE TABLE models(id INTEGER PRIMARY KEY, barcode TEXT, type TEXT, brand TEXT, color TEXT, gender TEXT, price REAL, total INTEGER)',
      );
    });
  }

Dependencies:

dependencies:
  flutter_svg: 2.0.4
  sqflite: 2.2.8
  path_provider: 2.0.14
  flutter:
    sdk: flutter

In main.dart:

void main() async{
  await ModelDatabase.initdb();
  runApp(MyApp());
}

I'm getting this error:

Error: Bad state: databaseFactory not initialized

Also same error with example from official doc example from flutter https://docs.flutter.dev/cookbook/persistence/sqlite

I tried to run flutter clean and revalidate caches. Also not working. I'm using Android Studio 2022.1.1

Sombriks
  • 3,370
  • 4
  • 34
  • 54
ramdolpix
  • 23
  • 4

1 Answers1

0

I no longer remember where this is documented but typically you should add WidgetsFlutterBinding.ensureInitialized(); before using any plugin API before runApp is called:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await ModelDatabase.initdb();
  ...

See What Does WidgetsFlutterBinding.ensureInitialized() do?

alextk
  • 5,713
  • 21
  • 34