3

I am quite new to Flutter, and I am now trying to use its shared_preferences package for saving a String and retrieving it back.

Now, I believe getString should return a String (at least that's what VS Code tells me), so I declared a wrapper function that returns a String:

String getName() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString('name');
}

However, this does not compile, with the error (notice the missing quotation mark of 'String):

A value of type 'String can't be returned from method 'getName' because it has a return type of 'String'

If I remove the return type altogether, the error goes away:

getName() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString('name');
}

Can anyone explain what is going on here? What does getString actually return?

2 Answers 2

4

You have to return a Future as yours is an async function

Future<String> getName() async {
  final prefs = await SharedPreferences.getInstance();
  return prefs.getString('name');
}
Sign up to request clarification or add additional context in comments.

Comments

0

Okay, I now figured out what I was missing: my function is async!

And as it turns out, async function in Dart have a return type of Future.

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.