-2

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?>'

Daesslohnt
  • 13
  • 3
  • Does this answer your question? [A value of type 'String?' can't be assigned to a variable of type 'String'](https://stackoverflow.com/questions/66508574/a-value-of-type-string-cant-be-assigned-to-a-variable-of-type-string) – Md. Yeasin Sheikh Apr 01 '22 at 13:03

2 Answers2

2

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!);
}
Hamza Siddiqui
  • 675
  • 5
  • 12
1

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.

eNeM
  • 482
  • 4
  • 13