我正在嘗試創建一個持久介面,它將資料庫呼叫分叉到 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
);
}
}
我應該如何回傳AppDatabase從init()?
uj5u.com熱心網友回復:
也許您應該將init()函式的型別更改AppDatabase為Future<AppDatabase>? 對我來說,代碼似乎是正確的,應該回傳AppDatabase.
uj5u.com熱心網友回復:
init 方法回傳一個未來,因為你在等待它(這是一種推薦的方式)
如果您只想回傳 AppDatabase,請按如下方式重寫:
static AppDatabase init() {
return $FloorAppDatabase.databaseBuilder(m_work_config.mWorkFloorDb).build().then((AppDatabase db) => db);}
這樣做會產生一些影響,但這不會被等待,這意味著任何依賴于此的呼叫都會延遲回傳..
我建議對被呼叫者使用 await 子句,
例如
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*/});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377562.html
上一篇:Flutter例外無法決議com.google.android.gms:play-services-location:16.
