簡體   English   中英

如何從祖先小部件更改文本字段的顏色?

[英]How to change color of text field from ancestor widget?

想象一下,我有一個這樣的小部件:

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

fgColor MyWidgetchild文本?

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

你的child可以是任何Widget ,所以這實際上是不可能的。 但是,如果您仍然想通過一些解決方法來 go,那么您正在尋找以下內容:

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);
  }
}

用法:

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

在此處輸入圖像描述

看起來我可以為此使用ColorFiltered

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

在此處輸入圖像描述

似乎我應該能夠通過在孩子上方提供DefaultTextStyle來做到這一點,但我似乎無法讓它工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM