Flutter:如何获取除2个键之外的所有SharedPreferences键

时间:2019-04-17 18:03:12

标签: flutter sharedpreferences

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

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

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

我期望输出:除(“ lib_cached_image_data”,值),(“ lib_cached_image_data_last_clean”,值)之外的所有(“键”,“值”)

2 个答案:

答案 0 :(得分:2)

您可以使用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);

答案 1 :(得分:0)

实现您的代码,如下所示:

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);
相关问题