Dart: A value of type 'String?' can't be assigned to a variable of type 'String'

2.3k Views Asked by At

There are 2 functions. One must return String other save this String in with SharedPreferences. The problem is, that by using prefs.getString() I get not a String but another object. The error called: A value of type 'String?' can't be assigned to a variable of type 'String'.

  getCurrentCityFromSharedPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('currentCity');
  }

  Future<void> setCurrentCityInSharedPreferences(String newCity) async{
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('currentCity', newCity);
  }

I have tried to rewrite function to

Future<String?> getCurrentCityFromSharedPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('currentCity');
  }

but then I get as string Deskription of object: Instance of 'Future<String?>'

2

There are 2 best solutions below

0
On

your set string type is simply string and get type is String? so change set type like this

 Future<void> setCurrentCityInSharedPreferences(String? newCity) async{
final prefs = await SharedPreferences.getInstance();
prefs.setString('currentCity', newCity!);
}
0
On

When you try to get currentCity from SharedPreferences you get an object of type String?. This basically means that the returned object is a string that can also be null (in case there is no data stored with the key currentCity in SharedPreferences).

So, you can't do something like:

String s = prefs.getString('currentCity');

You have to handle the possibility of the value being null.

You can either declare the variable as String? like this:

String? s = prefs.getString('currentCity');

Or you can do something like:

String s = prefs.getString('currentCity') ?? "No City";

So, if you want to handle null values in the getCurrentCityFromSharedPreferences function then what you can do is:

Future<String> getCurrentCityFromSharedPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString('currentCity') ?? "No City";
}

You can replace "No City" with any value that you want to show when there is no city saved in SharedPreferences.