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.
CodePudding user response:
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.
