0

While using shared prefs plugin it's common to explore code like below

void saveList() async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setStringList("listKey", aList); //await isn't used
}

where setStringList returns a Future<bool> so that why in this case the await isn't used.

rozerro
  • 5,787
  • 9
  • 46
  • 94

1 Answers1

1

await isn't used in your example because it wouldn't do anything and therefore would be unnecessary.

The purpose of await is to make subsequent code wait for the Future to complete. That is, if you have:

await foo();
bar();

then your program would wait for foo() to asynchronously complete before invoking bar().

If you have:

Future<void> baz() async {
  await foo();
}

that's implicitly equivalent to:

Future<void> baz() async {
  await foo();
  return;
}

and your program would wait for foo() to asynchronously complete before "returning" from baz(). ("Returning" from an asynchronous function actually means completing the returned Future.)

In your example:

void saveList() async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setStringList("listKey", aList);
}

There is nothing left to do after prefs.setStringList completes. There is no code afterward that depends on its completion, neither in saveList itself nor in saveList's callers. (Since saveList returns void instead of a Future, it is a "fire-and-forget" function; callers cannot wait for it to complete even if they wanted to.) Therefore, using await prefs.setStringList(...) wouldn't change any behavior and wouldn't serve any purpose.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • What if the list is somehow weights and I do something like (in button): `onPressed() async { await saveList(); setState(); }` where in rebuild some saved data should be used. Is it possible that in `build()` those data could be requested before the data will be saved in `saveList` ? – rozerro May 04 '23 at 07:49
  • @rozerro `await saveList()` is wrong. As I already explained, `saveList()` does not return a `Future`. – jamesdlin May 04 '23 at 10:58
  • yea, I meant if the `saveList()` would have a signature `Future` (it's still a legal signature for the `saveList()` func) – rozerro May 04 '23 at 13:03
  • @rozerro If `saveList` did return a `Future`, then it would need `await prefs.setStringList(...)`. Without that, `saveList` would signal completion before the preferences would finish being saved. – jamesdlin May 04 '23 at 14:39