Search code examples
flutterdartsharedpreferences

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


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?


Solution

  • 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]);