Suppose I want to initialize a text field by using the initialValue: property on a TextFormField, and I need my initial value to come from a provider. I read on the docs that calling read() from inside the build method is considered bad practice, but calling from handlers is fine (like onPressed). So I'm wondering if its fine to call read from the initialValue property like shown below?
Flutter Riverpod - using read() inside build method
2.9k Views Asked by AudioBubble At
1

No, you should use
useProviderif you are using hooks, or aConsumerWidget/Consumerif you are not.The difference being, the
initialValuefield is a part of the build method, and like you said,onPressedis a handler, outside of the build method.A core aspect of providers is optimizing rebuilds as provided values change. Using
context.readin the build method is nullifying this benefit as you aren't listening to the provided value.Using
context.readis highly recommended in anonymous functions (onChanged,onPressed,onTap, etc.) because those functions are retrieving the provided value at the time the function is executed. This means the function will always execute with the current value of that provider, without having to listen to the provider. The other methods for reading providers use a listener which is more expensive and unnecessary in the case of anonymous functions.In your example, you wanted to set
initialValueof aTextFormField. The following is how you could use hooks_riverpod and flutter_hooks to accomplish that.And for readers who prefer to not use hooks:
Or:
The primary difference being that
Consumerwill only rebuild its children because only they are relying on provided data.