Home > Software engineering >  How to change color of text field from ancestor widget?
How to change color of text field from ancestor widget?

Time:01-24

Imagine I have a widget like this:

MyWidget(
  fgColor: Colors.red,
  child: Text('Hello', style: MyStyles.someStaticStyle);
)

Is there any way that MyWidget can assign the fgColor to the child text?

Widget build(context){
  return child; // How to apply fgColor to this?
}

CodePudding user response:

Your child could be any Widget, so it's practically not possible. But if you still want to go with some workaround, here is what you're looking for:

class MyWidget extends StatelessWidget {
  final Color? fgColor;
  final Widget child;

  const MyWidget({
    Key? key,
    this.fgColor,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Widget widget = child;
    if (widget is Text) {
      return Text(
        widget.data!,
        style: widget.style != null ? widget.style!.copyWith(color: fgColor) : TextStyle(color: fgColor),
      );
    }

    return Container(color: fgColor, child: child);
  }
}

Usage:

Column(
  children: [
    MyWidget(
      fgColor: Colors.red,
      child: Text('Hello'), // Red color 'Hello'
    ),
    MyWidget(
      fgColor: Colors.red,
      child: SizedBox.square(dimension: 40), // Red color box
    ),
  ],
)

enter image description here

CodePudding user response:

Looks like I can use ColorFiltered for this:

return ColorFiltered(
  colorFilter: ColorFilter.mode(fgColor, BlendMode.srcIn),
  child: children);

enter image description here

Seems like I should be able to do this by providing a DefaultTextStyle above the child, but I couldn't seem to make it work.

  •  Tags:  
  • Related