Home > Blockchain >  import database provider to another file provider dart
import database provider to another file provider dart

Time:08-29

I want consume my db connection provider in many independents providers file.

How can I get my DBProvider (mainProvider.dart) into one of them(i.e. langProvider.dart)

this is the code of both.

mainProvider.dart

class DBProvider{
  static Database? _database;
  static final DBProvider db = DBProvider._();

  DBProvider._();

  Future<Database> get database async{
    _database ??= await initDB();

    return _database!;
  }

  Future<Database> initDB() async{
    Directory documentDirectory = await getApplicationDocumentsDirectory();

    final path = join(documentDirectory.path, 'assets/database/myDB.db');
    await deleteDatabase(path);
    debugPrint(path);

    var existsDB = await databaseExists(path);

    if(!existsDB){
      try{
        await Directory(dirname(path)).create(recursive: true);
      } catch(_){}

      ByteData data = await rootBundle.load(join('assets/database/myDB.db'));
      List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      await File(path).writeAsBytes(bytes, flush: true);
    }

    var db = await openDatabase(path);
    return db;
  }
}

langProvider.dart

import 'package:flutter_demo_app/src/providers/provider.dart';
import 'package:flutter_demo_app/src/models/lang_model.dart';

  Future<List<langModel>> getAllLangs() async{
    Database db = await database;
    final result = await db.query('languages');

    return result.isNotEmpty ? result.map((langs) => langModel.fromJson(langs)).toList() : [];
  }

  Future<langModel?> getLangById(int id) async{
    Database db = await database;
    final result = await db.query('languages', where: 'id = ?', whereArgs: [id]);

    return result.isNotEmpty ? langModel.fromJson(result.first) : null;
  }

CodePudding user response:

Use ProxyProvider to set the DBProvider into other providers. It's going to be something like this:

MultiProvider(providers: [
  Provider(create: (context) => DBProvider),
  ProxyProvider<DBProvider, LangProvider>(
    create: (context) => LangProvider(),
    update: (context, dbProvider, langProvider) =>
        langProvider..setDBProvider(dbProvider),
  ),
]),

The in the LangProvider create a setter to receive the DBProvider:

  DBProvider? _dbProvider;

  void setDBProvider(DBProvider dbProvider) {
    _dbProvider = dbProvider;
  }  

  Future<List<langModel>> getAllLangs() async{
    Database db = await _dbProvider!.database;
    final result = await db.query('languages');

    return result.isNotEmpty ? result.map((langs) => langModel.fromJson(langs)).toList() : [];
  }

  Future<langModel?> getLangById(int id) async{
    Database db = await _dbProvider!.database;
    final result = await db.query('languages', where: 'id = ?', whereArgs: [id]);

    return result.isNotEmpty ? langModel.fromJson(result.first) : null;
  }
  • Related