Home > Enterprise >  How to check if multiple values exist in shared preferences at once in flutter
How to check if multiple values exist in shared preferences at once in flutter

Time:08-26

I know how to check for a single key if exist in shared preferences like this line for example:

bool check = preferences.containsKey('weight');

But what if I want to check for multiple keys at once, something like this:

bool check = preferences.containsKey('weight','height',userName...ect);

Is is possible to somehow check for multiple values at once?

CodePudding user response:

Lets say you have a bunch of keys . All you need to do is do this operation over a list and then reduce that into one boolean value

Try this function

// Your function takes a string and checks 
bool myFunc(List<String> keys){

return keys.map((key)=>preferences.containsKey(key)).reduce((prev,next) => prev && next);


}

CodePudding user response:

There is no method in SharedPreferences to do that, but you can writen an extension method to make it look like there was:

extension SharedPreferencesExtensions on SharedPreferences {
  bool containsAllKeys(Iterable<String> keys) {
    return !keys.any((key) => !this.containsKey(key));
  }
}

Now you can call it like this:

bool check = preferences.containsAllKeys(['weight','height',userName...ect]);

CodePudding user response:

You could write two helper functions:

/// Will return a map with etries like the folllowing:
///
/// {
///   'weight': true,
///   'height': false,
///   'username': true,
/// }
Map<String, bool> containsKeyMulti(List<String> keys) {
  var containsKeyMap = <String, bool>{};

  for (var key in keys) {
    containsKeyMap[key] = preferences.containsKey(key);
  }

  return containsKeyMap;
}

/// Will return a bool value whether all keys are present
bool doesContainAllKeys(List<String> keys) {
  var containsKeyMap = containsKeyMulti(keys);
  return containsKeyMap.values.every((value) => true);
}

Usage:

var interestedKeys = <String>['weight', 'height', 'userName'];
var containsKeysMap = containsKeyMulti(interestedKeys);
var containsAllKeys = doesContainAllKeys(interestedKeys);
  • Related