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.
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.