Home > Software design >  prefs.getString telling me that a String is a String?
prefs.getString telling me that a String is a String?

Time:08-13

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;
    }

CodePudding user response:

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());

CodePudding user response:

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;
    }
  }

CodePudding user response:

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');

  • Related