我正在尝试创建一个持久接口,将数据库调用分支到floor或另一个自制的web数据库静态存储。
不管怎样。。。
接口部分如下所示:peristent_interface.dart
import 'package:flutter/material.dart';
import 'package:mwork/database/floor/entities/map_location_entity.dart';
import 'package:mwork/database/floor/result/map_location_result.dart';
import 'persistent_stub.dart'
if(dart.library.io) 'persistent_native.dart'
if(dart.library.js) 'persistent_web.dart';
abstract class Persistent extends ChangeNotifier {
static Persistent? _instance;
static Persistent? get instance{
_instance ??= getPersistent();
return _instance;
}
Future<List<MapLocationResult?>?> getMapLocations();
Future<MapLocationResult?> getMapLocation({int id});
Future<void> insertReplaceMapLocation(MapLocation mapLocation);
Future<void> insertReplaceMapLocations(List<MapLocation> mapLocations);
}
到目前为止,一切似乎都很好,但当下面的init()
函数返回Future<AppDatabase>
而不是我想要的AppDatabase
时,问题就出现了。
persistent_native.dart
import 'package:floor/floor.dart';
import 'package:mwork/database/floor/database/database.dart';
import 'package:mwork/database/floor/entities/map_location_entity.dart';
import 'package:mwork/database/floor/result/map_location_result.dart';
import 'package:mwork/services/persistent/persistent_interface.dart';
import 'package:mwork/common/m_work_config.dart' as m_work_config;
Persistent getPersistent() => PersistentNative();
class PersistentNative extends Persistent {
final AppDatabase _appDatabase = init(); //<-- Fails here !!
static Future<AppDatabase> init() async {
return await $FloorAppDatabase.databaseBuilder(m_work_config.mWorkFloorDb).build();
}
@override
Future<List<MapLocationResult?>?> getMapLocations() async {
return await _appDatabase.mapLocationDao.getMapLocations();
}
@override
Future<MapLocationResult?> getMapLocation({int id=-1}) async {
return await _appDatabase.mapLocationDao.getMapLocation(id);
}
@override
Future<void> insertReplaceMapLocation(MapLocation mapLocation) async {
_appDatabase.mapLocationDao.insertMapLocation(
mapLocation
);
}
@override
Future<void> insertReplaceMapLocations(List<MapLocation> mapLocations) async {
_appDatabase.mapLocationDao.insertMapLocations(
mapLocations
);
}
}
我应该如何从init()
返回AppDatabase
?
也许您应该将init()
函数的类型更改为AppDatabase
而不是Future<AppDatabase>
?对我来说,这段代码似乎是正确的,应该返回AppDatabase
。
init方法返回一个future,因为您在等待它(这是一种推荐的方式(
如果您只想返回AppDatabase,请按以下方式重写它::
static AppDatabase init() {
return $FloorAppDatabase.databaseBuilder(m_work_config.mWorkFloorDb).build().then((AppDatabase db) => db);}
这样做会有一些影响,但这不会被等待,这意味着任何依赖于此的电话都会延迟返回。。
我建议对被叫使用wait子句
例如
static Future<AppDatabase> init() async {
return await $FloorAppDatabase.databaseBuilder(m_work_config.mWorkFloorDb).build();
}
然后将其称为:
final AppDatabase db = await (...........);
或:::
YourClass.init().then((AppDatabase db) { /* anything here*/});