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 thefindAncestorWidgetOfExactTypemethod like this:As you see in the example, I wrapped the
Textwidget with aBuilderto give it a newBuildContextso I can start searching from it ( not wrapping with theBuilderwidget will make the look-up start from theBuildContextof thebuild(), which exclude the currentWidgettree, which is not what we want ).Then, starting the lookup with
findAncestorWidgetOfExactType<Container>(), In my example I have the parent as aContainerso 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.