如何在Android端访问Flutter共享首选项(使用Java)
问题内容:
我在dart中具有以下功能来设置特定的布尔首选项值。
_switchPersistentNotifications() {
setState(() {
isPersistentNotificationEnabled = !isPersistentNotificationEnabled;
});
widget.preferences.setBool(
"isPersistentNotificationEnabled", isPersistentNotificationEnabled);
}
此功能设置isPersistentNotificationEnabled
首选项的值。
现在在本机android端,我应该使用此共享的首选项值。到目前为止,这是我所做的。
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the state change notification is to be shown
if (preferences.getBoolean("flutter.isStateChangeNotificationEnabled", false)) {
showConnectionStateChangeNotification();
}
而且if条件永远不会被评估为真。我还尝试使用下面的代码打印所有现有的首选项值。
Map<String, ?> allEntries = preferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
并且仅显示Android创建的值(使用java)。
非常感谢您对使用偏好值的任何帮助。谢谢。
问题答案:
抱歉,这个答案来晚了,刚从github的flutter中得到了答案。
您可以做到的是:
SharedPreferences prefs = getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
然后,如果您想阅读例如“ myValue”键,则必须添加“ flutter”。字首:
String value = prefs.getString("flutter."+key, null);