[英]how to change a text widget's text and color/button's widget text and color dynamically?
[英]How to change color of text field from ancestor widget?
想象一下,我有一個這樣的小部件:
MyWidget(
fgColor: Colors.red,
child: Text('Hello', style: MyStyles.someStaticStyle);
)
fgColor
MyWidget
給child
文本?
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
),
],
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.