【发布时间】:2020-09-04 02:44:40
【问题描述】:
在我的应用程序中,我正在使用sembast db,并且我正在尝试将AppDatabase 单例类调整为依赖于平台并在应用程序在网络上运行时使用sambast_web。
我正在尝试使用与用户位置相同的模式,因此我创建了:
- 带有 getter 方法的存根。
-
abstract class AppDatabase在导入存根时对设备和网络包进行条件包导入,并在类工厂方法中返回存根 getter 方法。 -
class AppDatabaseDevice和class AppDatabaseWeb都实现了AppDatabase。
运行应用程序时出现错误:
Compiler message:
lib/fixit_shop_app/database/app_database_switcher.dart:50:28: Error: Method not found: 'getAppDatabase'.
factory AppDatabase() => getAppDatabase();
^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
Failed to build bundle.
Error launching application on iPad (6th generation).
现在,这很奇怪,因为在为抽象类工厂编写代码时它发现 getAppDatabase() 并没有抛出任何错误。
在对代码进行了一些操作后,我确定了存根导入的条件导入问题。
如果我在没有条件导入的情况下导入它
import 'package:fixit_shop_flutter/fixit_shop_app/database/app_database_stub.dart';
然后我没有收到任何错误,但我确实需要条件导入..
你能发现为什么这个类的条件导入失败而对另一个类有效吗?
一如既往地非常感谢您的时间和帮助。 这些是 AppDatabase 方法:
存根:
import 'app_database_switcher.dart';
AppDatabase getAppDatabase() => throw UnsupportedError(
'Cant get AppDatabase if not loading the right package');
抽象类:
import 'dart:async';
import 'package:sembast/sembast.dart';
import 'app_database_stub.dart'
if (dart.library.io) 'package:sembast/sembast.dart'
if (dart.library.js) 'package:sembast_web/sembast_web.dart';
abstract class AppDatabase {
// Singleton instance
static final AppDatabase _singleton;
// Singleton accessor
static AppDatabase get instance => _singleton;
// Completer is used for transforming synchronous code into asynchronous code.
Completer<Database> _dbOpenCompleter;
// A private constructor. Allows us to create instances of AppDatabase
// only from within the AppDatabase class itself.
// Sembast database object
Database _database;
// Database object accessor
Future<Database> get database async {
// // If completer is null, AppDatabaseClass is newly instantiated, so database is not yet opened
return _dbOpenCompleter.future;
}
factory AppDatabase() => getAppDatabase();
}
这是用户定位方法:
存根:
import 'package:fixit_shop_flutter/fixit_shop_app/platform_user_location/user_location_switcher.dart';
UserLocation getUserLocation() =>
throw UnsupportedError('user_location_stub error');
抽象类:
import 'package:fixit_shop_flutter/fixit_shop_app/platform_user_location/user_location_stub.dart' // Version which just throws UnsupportedError
if (dart.library.io) "package:fixit_shop_flutter/fixit_shop_app/platform_user_location/user_location_device.dart"
if (dart.library.js) "package:fixit_shop_flutter/fixit_shop_app/platform_user_location/user_location_web.dart";
abstract class UserLocation {
// methods to be used
Future<Map<String, dynamic>> getPosition() async {
Future<Map<String, dynamic>> position;
return position;
}
factory UserLocation() => getUserLocation();
}
【问题讨论】: