如何在Flutter / Dart中导入特定于平台的依赖项?(结合使用Android / iOS的Web)


9

shared_preferences在适用于iOS和Android的Flutter应用程序中使用。在网络上,我正在使用http:dart依赖项(window.localStorage)本身。由于Flutter for Web已合并到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];

等等。在没有这些错误的情况下,如何根据平台使用不同的方法/类?请注意,我以这种方式使用了更多的依赖关系,而不仅仅是首选项。谢谢!


据我所知,您不应在同一方法或类中同时拥有localstorageshared preferences依赖项。这意味着编译器无法对这两个依赖项进行树状交换。理想情况下,导入应隐藏这些实现。我将尝试提出一个清晰的实施示例。
Abhilash Chandran,

您可以使用全局布尔型kIsWeb,它可以告诉您该应用程序是否已编译为可以在网络上运行。文档:api.flutter.dev/flutter/foundation/kIsWeb-constant.html if(kIsWeb){//在网络上运行!初始化网络数据库} else {//使用共享的首选项}
Shamik Chodankar

Answers:


20

这是我处理您问题的方法。这基于此处的http package中的实现。

核心思想如下。

  1. 创建一个抽象类来定义您将需要使用的方法。
  2. 创建特定于实现webandroid依赖关系的实现,以扩展此抽象类。
  3. 创建一个存根,该存根公开一个方法以返回此抽象实现的实例。这只是为了使飞镖分析工具保持满意状态。
  4. 在抽象类中,导入此存根文件以及特定于mobile和的条件导入web。然后在其工厂构造函数中返回特定实现的实例。如果编写正确,将通过条件导入自动处理。

步骤1和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();
}

步骤2.1:Web密钥查找器

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();

步骤2.2:移动钥匙查找器

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();

步骤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抽象类时,就好像它是一个通用实现。这有点像适配器模式

main.dart

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;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

一些屏幕截图

网页 在此处输入图片说明 在此处输入图片说明

移动 在此处输入图片说明


2
感谢您的辛勤工作!做得好。同时,我也以相同的方式(也在http包中查找,这很有趣:))。非常感谢!
乔瓦尼

1
希望这对其他人也有帮助。我们都通过解决来学习.. :-)
Abhilash Chandran

您好尝试过您的代码工作!ty。然后,我发现了有关全局布尔值kIsWeb的信息,它可以告诉您是否已将该应用程序编译为可在网络上运行。说明文件:api.flutter.dev/flutter/foundation/kIsWeb-constant.html PS-如果我忽略某些实现,则可以提前对歉意表示歉意
Shamik Chodankar

2
@ShamikChodankar你说得对。此布尔值标志将有助于某些合理的决策。OP也尝试过此选项。但是问题是,如果我们dart:html' and 在同一个函数中同时使用这两个sharedpreferences,则编译器将生成错误,因为它不知道dart:html何时针对移动设备进行编译,相反,sharedpreferences除非针对它的作者,否则它将不知道何时针对Web进行编译内部处理。如果您有使用此标志的有效示例,请共享。我也是新手:)。
Abhilash Chandran
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.