将数据库提供程序导入另一个文件提供程序dart



我想在许多独立的提供者文件中使用我的数据库连接提供者。

我如何将我的DBProvider(mainProvider.dart(放入其中一个(即langProvider.dar(

这是两者的代码。

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;
}

使用ProxyProviderDBProvider设置为其他提供程序。它将是这样的:

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

LangProvider中的创建一个setter以接收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;
}

相关内容

  • 没有找到相关文章

最新更新