【发布时间】:2020-09-20 16:31:28
【问题描述】:
我有以下问题:现在 PlayStore 中有一个用本机代码(iOS 和 Android)编写的应用程序,我计划将其迁移到 Flutter。我的目标是用户不会注意到引擎盖下的变化,但可以像以前一样继续使用该应用程序。为此,我还需要迁移共享首选项。然而,这是相当困难的。在原生 Android 应用程序中,我存储了相关的共享偏好,如下所示:
SharedPreferences sharedPrefs = context.getSharedPreferences(
"storage",
Context.MODE_PRIVATE
);
sharedPrefs.putString('guuid', 'guuid_value');
editor.apply();
这会导致在此路径创建文件:
/data/data/patavinus.patavinus/shared_prefs/storage.xml
包含以下内容:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="guuid" value="guuid_value" />
</map>
如果我在 Flutter 中使用 shared_prefences 来获取这个值:
final sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.getString('guuid');
它返回 null 因为它正在寻找
/data/data/patavinus.patavinus/shared_prefs/FlutterSharedPreferences.xml 这是在 Flutter 中使用 shared_preferences 存储共享首选项时写入的文件。因为共享首选项是在本机应用程序上下文中编写的,所以文件显然不存在。
有没有什么方法可以让 Flutter 在不使用平台通道的情况下寻找/data/data/patavinus.patavinus/shared_prefs/storage.xml?
我知道它是如何工作的,就像这里提到的那样:How to access flutter Shared preferences on the android end (using java)。这种方式很简单,因为在 Android 中你可以选择在 Flutter 的前缀前面加上前缀。但是,在 Flutter 中你不能。
我也知道这个插件:https://pub.dev/packages/native_shared_preferences 但是,我不敢相信第三方插件是推荐的方式。此外,我将相关的共享首选项分布在多个资源文件中。在这个插件中,你只能设置一个(通过指定字符串资源flutter_shared_pref_name)。
【问题讨论】:
-
您可以使用
MethodChannels。见this article。 -
他说他不想使用
PlatformChannel -
Flutter 使用它自己的 sharedprefs 名称 github.com/flutter/plugins/blob/master/packages/… 在这里查看。如果您使用存储在 Android 首选项中的相同名称,那么我相信颤振 shared_prefs 可以读取。虽然没有测试
标签: flutter migration sharedpreferences flutter-platform-channel