Sometimes it is quite tricky to work with riverpod
providers.
Especially, when you want to initialize a provider with an async value.
Showing the version of your app
Here, I show you how you can structure your app to resolve this issue. In this example, we are going to display the version of the app using the package_info_plus package.
If you check the package’s documentation, you can see that reading this information returns a Future
.
So how can we initialize a Provider
without making it a AsyncProvider
?
PackageInfo packageInfo = await PackageInfo.fromPlatform();
Example
The trick is to decouple awaiting the Future
and initializing the Provider.
We can use the loading time before the app actually starts to fetch the necessary information.
The user will probably see the splash screen for a couple of milliseconds longer, but later, we can synchronously access
the data.
We can then use riverpod Override
s to set the loaded data to a provider. Let’s have a look how this can look like:
You can find the source code of this example on GitHub: https://github.com/bettercoding-dev/riverpod-sync-provider-async-value
main.dart
|
|
Here, you can see that we call initGlobalProviders
right before we actually run the app.
The main
function can be async
, this means we can resolve our futures here.
Apps show a splash screen when staring. So all waiting done here will be done while the splash screen is shown.
We can then hand the overrides
to the ProviderScope
.
This is a riverpod
specific widget that contains all the providers states.
global_providers.dart
|
|
We use the global_providers.dart
file to define our PackageInfo
provider.
But instead of directly assigning a value to the provider, we’ll throw an error.
The initialization is done in the initGlobalProviders
function, which is then called in main.dart
as we saw
earlier.
We use the overrideWithValue
function of the provider to instead of throwing an error provide the given value.
version_page.dart
|
|
Finally, in the UI we can simply read the provider and then access the values without having to await
anything.
Summary
In this example I showed you how to structure your app to resolve Future
s before starting the app and using
Override
s update a providers value at a later time.