1

I am trying to save a string to shared preferences and then retrieve it.

However, my Android Studio tells me that there is an error.

Specifically, it says:

The argument type 'String?' can't be assigned to the parameter type 'String'. However, I don't know what it is referring to as I don't think I ever specify that the variable is a String?.

Here is the code:

  void _setFirstAppLaunchDate(DateTime value) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('firstLaunchDate', value.toString());
  }

  Future<DateTime> getFirstAppLaunchDate() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getString('firstLaunchDate') != null)
      return DateTime.parse(prefs.getString('firstLaunchDate'));
    else {
      var now = DateTime.now();
      _setFirstAppLaunchDate(now);
      return now;
    }

3 Answers 3

1
return DateTime.parse(prefs.getString('firstLaunchDate'));

This may return null value instead of string. That's what is mentioned as String? you can assign a placeholder value if its null like the following

return DateTime.parse(prefs.getString('firstLaunchDate')??DateTime.now().toString());
Sign up to request clarification or add additional context in comments.

Comments

1

prefs.getString('firstLaunchDate') can return null. Therefore, it is showing this error. While you've already done with null check, you add ! end of it.

 if (prefs.getString('firstLaunchDate') != null)
      return DateTime.parse(prefs.getString('firstLaunchDate')!);

I think better way will be creating a varible

  Future<DateTime> getFirstAppLaunchDate() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    final firstData = prefs.getString('firstLaunchDate');

    if (firstData != null) {
      return DateTime.parse(firstData);
    } else {
      var now = DateTime.now();
      _setFirstAppLaunchDate(now);
      return now;
    }
  }

Comments

1

You can also use this syntax to indicate a default value incase of a null value:

return DateTime.parse(prefs.getString('firstLaunchDate') ?? '1980-01-01');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.