【发布时间】:2020-03-01 18:16:00
【问题描述】:
我在 iOS 和 Android 的 Flutter 应用程序中使用 shared_preferences。在网络上,我正在使用 http:dart 依赖项 (window.localStorage) 本身。由于 Flutter for web 已合并到 Flutter repo,我想创建一个跨平台解决方案。
这意味着我需要导入两个单独的 API。这似乎在 Dart 中还没有得到很好的支持,但这就是我所做的:
import 'package:some_project/stub/preference_utils_stub.dart'
if (dart.library.html) 'dart:html'
if (dart.library.io) 'package:shared_preferences/shared_preferences.dart';
在我的preference_utils_stub.dart 文件中,我实现了所有需要在编译期间可见的类/变量:
Window window;
class SharedPreferences {
static Future<SharedPreferences> get getInstance async {}
setString(String key, String value) {}
getString(String key) {}
}
class Window {
Map<String, String> localStorage;
}
这会在编译之前消除所有错误。现在我实现了一些方法来检查应用程序是否正在使用网络:
static Future<String> getString(String key) async {
if (kIsWeb) {
return window.localStorage[key];
}
SharedPreferences preferences = await SharedPreferences.getInstance;
return preferences.getString(key);
}
但是,这会产生大量错误:
lib/utils/preference_utils.dart:13:7: Error: Getter not found:
'window'.
window.localStorage[key] = value;
^^^^^^ lib/utils/preference_utils.dart:15:39: Error: A value of type 'Future<SharedPreferences> Function()' can't be assigned to a
variable of type 'SharedPreferences'.
- 'Future' is from 'dart:async'.
- 'SharedPreferences' is from 'package:shared_preferences/shared_preferences.dart'
('../../flutter/.pub-cache/hosted/pub.dartlang.org/shared_preferences-0.5.4+3/lib/shared_preferences.dart').
SharedPreferences preferences = await SharedPreferences.getInstance;
^ lib/utils/preference_utils.dart:22:14: Error: Getter not found:
'window'.
return window.localStorage[key];
等等。如何在没有这些错误的情况下根据平台使用不同的方法/类?请注意,我以这种方式使用更多依赖项,而不仅仅是首选项。谢谢!
【问题讨论】:
-
在我有限的知识中,您不应该在同一方法或类中同时拥有
localstorage和shared preferences依赖项。这意味着编译器无法对这些依赖项中的任何一个进行树摇。理想情况下,导入应该隐藏这些实现。我将尝试提出一个清晰的实现示例。 -
您可以使用全局布尔 kIsWeb,它可以告诉您应用程序是否已编译为在 Web 上运行。文档:api.flutter.dev/flutter/foundation/kIsWeb-constant.html if (kIsWeb) { // 在网络上运行!初始化网络数据库 }else{ // 使用共享首选项 }
标签: flutter dart flutter-web