I want change a color of a button depending by background color of with:
computeLuminance()
So, I need to get parent widget located by button and get its color / any that can I calculate difference between the two colors.
Color calculateTextColor(Color background) {
return background.computeLuminance() >= 0.5 ? Colors.black : Colors.white;
}
I need to pass background color as exact parent color widget.
You can get a parent property ( color ) by referring to it using the
BuildContext
, and thefindAncestorWidgetOfExactType
method like this:As you see in the example, I wrapped the
Text
widget with aBuilder
to give it a newBuildContext
so I can start searching from it ( not wrapping with theBuilder
widget will make the look-up start from theBuildContext
of thebuild()
, which exclude the currentWidget
tree, which is not what we want ).Then, starting the lookup with
findAncestorWidgetOfExactType<Container>()
, In my example I have the parent as aContainer
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.