0

我正在尝试创建一个持久接口,它将 db 调用分叉到 floor 或另一个自制的 web db 静态存储。

反正...

接口部分如下所示: 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()

4

2 回答 2

0

也许您应该将init()函数的类型更改为AppDatabase而不是Future<AppDatabase>? 对我来说,代码似乎是正确的,应该返回AppDatabase

于 2021-12-08T18:24:09.860 回答
0

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*/});
于 2021-12-08T18:37:19.077 回答