我在iOS和Android的Ffltter应用程序中使用了shared_preferences.在网络上,我使用的是http:dart依赖项(window.localStorage)本身.由于腹板的Flutter 被合并到Flutter 回放中,我想创建一个跨平台的解决方案.

这意味着我需要导入两个单独的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;
}

这将消除编译前的所有错误.现在,我实现了一些方法来判断应用程序是否正在使用Web:

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];

等等如何根据平台使用不同的方法/类而不出现这些错误?请注意,我以这种方式使用了更多依赖项,而不仅仅是首选项.谢谢

推荐答案

以下是我对您的问题的处理方法.这是基于http包的实现,如在here中一样.

其核心思想如下.

  1. 创建一个抽象类来定义需要使用的方法.
  2. 创建特定于扩展此抽象类的webandroid依赖项的实现.
  3. 创建一个存根,它公开一个方法来返回这个抽象实现的实例.这只是为了让dart分析工具满意.
  4. 在抽象类中,导入此存根文件以及特定于mobileweb的条件导入.然后在其工厂构造函数中返回特定实现的实例.如果写入正确,这将由条件导入自动处理.

Step-1 and 4:

import 'key_finder_stub.dart'
    // ignore: uri_does_not_exist
    if (dart.library.io) 'package:flutter_conditional_dependencies_example/storage/shared_pref_key_finder.dart'
    // ignore: uri_does_not_exist
    if (dart.library.html) 'package:flutter_conditional_dependencies_example/storage/web_key_finder.dart';

abstract class KeyFinder {

  // some generic methods to be exposed.

  /// returns a value based on the key
  String getKeyValue(String key) {
    return "I am from the interface";
  }

  /// stores a key value pair in the respective storage.
  void setKeyValue(String key, String value) {}

  /// factory constructor to return the correct implementation.
  factory KeyFinder() => getKeyFinder();
}

Step-2.1: Web Key finder

import 'dart:html';

import 'package:flutter_conditional_dependencies_example/storage/key_finder_interface.dart';

Window windowLoc;

class WebKeyFinder implements KeyFinder {

  WebKeyFinder() {
    windowLoc = window;
    print("Widnow is initialized");
    // storing something initially just to make sure it works. :)
    windowLoc.localStorage["MyKey"] = "I am from web local storage";
  }

  String getKeyValue(String key) {
    return windowLoc.localStorage[key];
  }

  void setKeyValue(String key, String value) {
    windowLoc.localStorage[key] = value;
  }  
}

KeyFinder getKeyFinder() => WebKeyFinder();

Step-2.2: Mobile Key finder

import 'package:flutter_conditional_dependencies_example/storage/key_finder_interface.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefKeyFinder implements KeyFinder {
  SharedPreferences _instance;

  SharedPrefKeyFinder() {
    SharedPreferences.getInstance().then((SharedPreferences instance) {
      _instance = instance;
      // Just initializing something so that it can be fetched.
      _instance.setString("MyKey", "I am from Shared Preference");
    });
  }

  String getKeyValue(String key) {
    return _instance?.getString(key) ??
        'shared preference is not yet initialized';
  }

  void setKeyValue(String key, String value) {
    _instance?.setString(key, value);
  }

}

KeyFinder getKeyFinder() => SharedPrefKeyFinder();

Step-3:

import 'key_finder_interface.dart';

KeyFinder getKeyFinder() => throw UnsupportedError(
    'Cannot create a keyfinder without the packages dart:html or package:shared_preferences');

然后在main.dart中使用KeyFinder抽象类,就好像它是一个通用实现一样.这有点像adapter pattern.

100

import 'package:flutter/material.dart';
import 'package:flutter_conditional_dependencies_example/storage/key_finder_interface.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    KeyFinder keyFinder = KeyFinder();
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SafeArea(
        child: KeyValueWidget(
          keyFinder: keyFinder,
        ),
      ),
    );
  }
}

class KeyValueWidget extends StatefulWidget {
  final KeyFinder keyFinder;

  KeyValueWidget({this.keyFinder});
  @override
  _KeyValueWidgetState createState() => _KeyValueWidgetState();
}

class _KeyValueWidgetState extends State<KeyValueWidget> {
  String key = "MyKey";
  TextEditingController _keyTextController = TextEditingController();
  TextEditingController _valueTextController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Container(
        width: 200.0,
        child: Column(
          children: <Widget>[
            Expanded(
              child: Text(
                '$key / ${widget.keyFinder.getKeyValue(key)}',
                style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
              child: TextFormField(
                decoration: InputDecoration(
                  labelText: "Key",
                  border: OutlineInputBorder(),
                ),
                controller: _keyTextController,
              ),
            ),
            Expanded(
              child: TextFormField(
                decoration: InputDecoration(
                  labelText: "Value",
                  border: OutlineInputBorder(),
                ),
                controller: _valueTextController,
              ),
            ),
            RaisedButton(
              child: Text('Save new Key/Value Pair'),
              onPressed: () {
                widget.keyFinder.setKeyValue(
                  _keyTextController.text,
                  _valueTextController.text,
                );
                setState(() {
                  key = _keyTextController.text;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

some screen shots

Web enter image description hereenter image description here

mobile enter image description here

Flutter相关问答推荐

Flutter版本3.19.2需要更新版本的Kotlin Gradle插件./android/build.gradle:ext.kotlin_version = latest-version>'

为什么Riverpod生成器在这种情况下不生成AsyncNotiator?

如何在Ffltter Chrome应用程序中使用webview_fltter_web显示自定义html而不是外部uri?

Android Studio中的Ffltter&;Couchbase:进程C:/Program Files/Git/bin/bash以非零退出值35结束

如何处理Flutter Riverpod异步通知器中的状态和数据库

使用GO_ROUTER在模式内导航

'Flutter的无效常数值错误

尽管 onCollision 处理了我的角色还是从平台上掉了下来

构建上下文不能跨异步间隙使用

为 flutter app/firebase 保存 chatgpt api-key 的正确方法是什么

围绕父组件旋转位置组件

使用 Play Integrity API 时,Firebase 电话身份验证问题缺少客户端标识符错误

如何在android中 Select 任何文件/文件路径 - Flutter

输入处于活动状态时如何设置文本字段标签的样式?

你如何在 Flutter 中组合两个数组?

Flutter/Dart 返回_Future的实例而不是实际的字符串值

Flutter 如何使用 ClipPath 编辑容器的顶部?

Flutter 错误:正文可能正常完成,导致返回null

Future.wait() 中的 futures 可以顺序调用吗?

在 Flutter 中更新对象实例属性的最佳实践是什么?该实例嵌套在提供程序类的映射中,如下所示