.family
Before reading this, consider reading about providers and how to read them.
In this part, we will talk in detail about the .family
provider modifier.
The .family
modifier has one purpose: Creating a provider from external values.
Some common use-cases for family
would be:
- Combining FutureProvider with
.family
to fetch aMessage
from its ID - Passing the current
Locale
to a provider, so that we can handle translations: - Connecting a provider with another provider without having access to its variable.
#
UsageThe way families works is by adding an extra parameter to the provider. This parameter can then be freely used in our provider to create some state.
For example, we could combine family
with FutureProvider to fetch
a Message
from its ID:
Then, when using our messagesFamily
provider, the syntax is slightly modified.
The usual syntax will not work anymore:
Instead, we need to pass a parameter to messagesFamily
:
info
It is possible to use a family with different parameters simultaneously.
For example, we could use a titleFamily
to read both the french and english
translations at the same time:
#
Parameter restrictionsFor families to work correctly, it is critical for the parameter passed to
a provider to have a consistent hashCode
and ==
.
Ideally the parameter should either be a primitive (bool/int/double/String),
a constant (providers), or an immutable object that overrides ==
and hashCode
.
autoDispose
when the parameter is not constant:#
PREFER using You may want to use families to pass the input of a search field to your provider.
But that value can change often and never be reused.
This could cause memory leaks as, by default, a provider is never destroyed even
if no-longer used.
Using both .family
and .autoDispose
fixes that memory leak:
#
Passing multiple parameters to a familyFamilies have no built-in support for passing multiple values to a provider.
On the other hand, that value could be anything (as long as it matches with the restrictions mentioned previously).
This includes:
- A tuple from tuple
- Objects generated with Freezed or built_value
- Objects using equatable
Here's an example using Freezed and equatable:
- Freezed
- Equatable