我shared_preferences在适用于 iOS 和 Android 的 Flutter 应用程序中使用。在网络上,我使用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';
Run Code Online (Sandbox Code Playgroud)
在我的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;
}
Run Code Online (Sandbox Code Playgroud)
这在编译之前消除了所有错误。现在我实现了一些检查应用程序是否正在使用网络的方法:
static Future<String> getString(String key) async {
if (kIsWeb) {
return window.localStorage[key];
}
SharedPreferences preferences = …Run Code Online (Sandbox Code Playgroud)