mariapapag
mariapapag

Reputation: 1

Flutter detect which color text is on top of

I want to find the color of the widget that is behind (z axis) a Text() widget. The Text() widget may be in front of a Stack(), Column(), Scaffold(), Container() or any other widget. I am not talking about the background color property that is found in text style. I should be able to use this method to get the color of any widget that the text may be shown on top of. Is there a way to do this using context, mediaQuery, widget tree, etc.?

Final goal is to use the background color to determine the color of the text (black or white).

It would have to be determined after widget is built, so that they layout is completely built, and the final position of the Text() widget is set. I want to avoid using GlobalKeys to determine position of background widget and text widget

I tried using scaffoldBackground color from the context, however that does not take into account the color of the widget that is behind the Text() in a Stack().

My widget tree looks like

Stack(
  children: [
    Container(
      height: Certain height // I do have access to this value
      color: Some color // I also have access to this value
    ),
    Column(
      children: children // A list of widgets, one of which may be Text(), nested
    )
  ]
)

Upvotes: 0

Views: 112

Answers (1)

La Pyae
La Pyae

Reputation: 509

You should pre-defined for your font theme in ThemeData() inside MaterialApp() widget and can customize and choice which font size and color want to use depend on your background color.

Color primaryColor = ColorConstant().primaryColor;
Color blackColor = ColorConstant().blackColor;
Color greenColor = ColorConstant().greenColor;
Color grayColor = ColorConstant().grayColor;
Color iconColor = ColorConstant().iconColor;

ThemeData themeData(){
  return ThemeData(
    primaryColor: primaryColor,
    scaffoldBackgroundColor: Colors.white,
    textTheme: textTheme(),
  );
}

TextTheme textTheme(){
  return TextTheme(
      bodyText1: TextStyle(
        color: blackColor,
        fontFamily: 'OpenSans',
      ),
      bodyText2: TextStyle(
        color: blackColor,
        fontFamily: 'OpenSans'
      ),
      headline5: TextStyle(
        color: blackColor,
        fontFamily: 'Lato',
        fontSize: 700
      ),

  );
}

Add this predefined themeData() to MaterialApp() and can use like that as below

Text(
                "Togethers",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: context.theme.textTheme.headline5
                    ?.copyWith(color: ColorConstant().colorOnTealColor),
              ),

For more detail about theme you can read in here. https://docs.flutter.dev/cookbook/design/themes

Upvotes: 0

Related Questions