【问题标题】:Flutter : How to Get all SharedPreferences keys except some KeysFlutter:如何获取除某些键之外的所有 SharedPreferences 键
【发布时间】:2019-04-17 18:03:12
【问题描述】:

我想获取除两个键之外的所有 SharedPreferences 键

我不能使用 getString(Key) 方法,因为有 N 个键。

Future<List<Widget>> getAllPrefs() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    // I won't print those two keys neither remove them
    // prefs.remove("lib_cached_image_data");
    // prefs.remove("lib_cached_image_data_last_clean");
    prefs.setString("Market", "position");
    prefs.setString("Home", "position");
    return prefs.getKeys().map<Widget>((key) {
      //this is incorrect
      if (key != "lib_cached_image_data" && key != "lib_cached_image_data") {
        ListTile(
          title: Text(key),
          subtitle: Text(prefs.get(key).toString()),
        );
      }
    }).toList(growable: false);
  }

我希望输出:所有 ("Keys", "Values") 除了 ("lib_cached_image_data",value) , ("lib_cached_image_data_last_clean",value)

【问题讨论】:

    标签: flutter sharedpreferences


    【解决方案1】:

    您可以使用where。不要忘记也返回ListTile

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.getKeys().where((String key) => key != "lib_cached_image_data" && key != "lib_cached_image_data").map<Widget>((key) {
        return ListTile(
          title: Text(key),
          subtitle: Text(prefs.get(key).toString()),
        );
    }).toList(growable: false);
    

    【讨论】:

    • 未处理异常:MissingPluginException(在通道 plugins.flutter.io/shared_preferences 上找不到方法 getAll 的实现)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2018-02-01
    • 2011-11-02
    相关资源
    最近更新 更多