当我写下面的代码时,我希望文本是红色的:
Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.copyWith(
bodyText2: TextStyle(color: Colors.red),
),
buttonTheme: Theme.of(context)
.buttonTheme
.copyWith(buttonColor: Colors.yellow),
),
child: Builder(
builder: (context) {
return Column(
children: [
Text('Flutter'),
Text('is awesome!'),
RaisedButton(
onPressed: () {},
child: Text('OK'),
)
],
);
},
),
)
但是文本是黑色的,而按钮是黄色的,如您所见: here
如您所见,Text
小部件忽略了主题中定义的样式,而 RaisedButton
则没有。为什么?
我知道我可以使用 DefaultTextStyle
来代替,但我试图理解为什么它不像我预期的那样工作。
答案 0 :(得分:1)
Text
小部件具有 style
属性。正如我们从 docs 中看到的:
If the [style] argument is null, the text will use the style from the
closest enclosing [DefaultTextStyle].
很明显,如果您没有像以前那样指定,Text 将使用来自 DefaultTextStyle
小部件(而不是来自 Theme
)的样式。如果您想使用主题中的样式,您应该明确指定它:
Text('Flutter', style: Theme.of(context).textTheme.bodyText2)
至于按钮 - 任何 MaterialButton 子项(也包括 RaisedButton)使用 ButtonTheme.of(context).textTheme
作为 textTheme
属性的默认值。