skip to Main Content

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.

2

Answers


  1. 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.

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search