Home > OS >  How to set null values in SharedPreferences?
How to set null values in SharedPreferences?

Time:12-02

Minimal reproducible code:

void main() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('key', null); // Error
}

How can I set a null value in shared_preferences


Note: I'm not looking for workarounds like, instead of null, use an empty string '' and then check for it.

CodePudding user response:

Shared preferences uses key value pairs to store data. Values can be of type int, double, string or bool. Afaik, null value is not supported.

For your purposes I would therefore suggest that if the value of the string you want to save is null, you remove any previous stored version of it from shared preferences. You can then detect the null by the absence of that key.

CodePudding user response:

You could remove the relevant entry using await prefs.remove('key'). That way when you call prefs.getString('key') you will get back null.

  • Related