SteAp
SteAp

Reputation: 11999

How to return from an async method?

Based on the SharedPreferences class, I try to retrieve a preference value like so:

String loadIPAddress() {

    SharedPreferences.getInstance().then((SharedPreferences prefs) {

      try {

        var loadedValue = prefs.getString('serverIPAddress');
        print('loadIPAddress <= ' + loadedValue);
        return loadedValue; // [1]

      } catch (e) {

        print('loadIPAddress <= NOPE');
        return '---'; [2]

      }
    });
  }

Unfortunately, this doesn't return a value each time.

Q: Does the 1 and [2] return statements return the value of loadIPAddress()?

Upvotes: 0

Views: 173

Answers (1)

Richard Heap
Richard Heap

Reputation: 51750

No, as you've guessed, those returns return from the then callback.

To return from loadIPAddress, refactor it like this:

Future<String> loadIPAddress() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  try {
    var loadedValue = prefs.getString('serverIPAddress');
    print('loadIPAddress <= ' + loadedValue);
    return loadedValue;
  } catch (e) {
    print('loadIPAddress <= NOPE');
    return '---';
  }
}

Note that having made loadIPAddress async, it now returns a Future, so you should call it like:

String ip = await loadIPAddress();
// or
loadIPAddress().then((String ip) {
  // do something with ip - probably setState
});

Upvotes: 2

Related Questions