You can get a parent property ( color ) by referring to it using the BuildContext
, and the findAncestorWidgetOfExactType
method like this:
Container(
width: 200,
height: 200,
color: Colors.green,
child: Builder(
builder: (context) {
return Text(
"Hello",
style: TextStyle(
color: context
.findAncestorWidgetOfExactType<Container>()
?.color
?.withGreen(255),
fontSize: 20,
),
);
},
),
),
As you see in the example, I wrapped the Text
widget with a Builder
to give it a new BuildContext
so I can start searching from it ( not wrapping with the Builder
widget will make the look-up start from the BuildContext
of the build()
, which exclude the current Widget
tree, which is not what we want ).
Then, starting the lookup with findAncestorWidgetOfExactType<Container>()
, In my example I have the parent as a Container
so I set its type as generic.
this will give accessibility to its properties, and get me it the same color.
the withGreen()
is just to clarify that it works.