Search code examples
flutterdartinherited-widget

How to access data of child widget in parent in flutter?


I want to know the value of a certain field in a child (or child of child) widget in the parent widget, only when I want to know it.
Using a Callback or InheritedWidget/Provider doesn't work in this case as it provides me information every time there's a change in the value in the child. I only require the child's value, when there's an action in the parent. So, listening to all the changes is an overhead.
Another option is using a key to fetch the information from the child, but the children can be multiple, so will have to create those many keys and somehow attaching them to the children. And keys are a bit expensive.
Another option would be to store instances of the children and getting value from it.

Every option seems like overkill for a simple task. I am favoring on the key approach as it gives a feeling that they were created for these types of scenarios. Does anyone know anything better for this situation?

A simple use case is:
Imagine a parent having a PageView in the middle and a next button. The page in the middle contains a slider which changes its value. When we press next, we wanna know what's the slider's final value is.


Solution

  • There's a reason why it seems so hard: you shouldn't.

    Widgets are purposefully very limited to enforce an uni-directional data-flow, which is critical for maintainability of larger apps.

    Instead of reading the state of your descendants, you should "lift the state up" through inherited-widgets and similar patterns.