为什么文本小部件不采用主题中定义的样式?



当我编写以下代码时,我希望文本是红色的:

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'),
)
],
);
},
),
)

,但文字是黑色的,而按钮是黄色的,你可以看到:

可以看到,Text小部件忽略了主题中定义的样式,而RaisedButton没有。为什么?

我知道我可以使用DefaultTextStyle代替,但我试图理解为什么不像我预期的那样工作。

Textwidget具有style属性。从文档中可以看到:

If the [style] argument is null, the text will use the style from the
closest enclosing [DefaultTextStyle].

很明显,如果你没有指定它,文本使用DefaultTextStyle小部件的样式(而不是Theme)。如果你想使用style from theme,你应该明确指定:

Text('Flutter', style: Theme.of(context).textTheme.bodyText2)

对于按钮-任何MaterialButton子(RaisedButton也是)使用ButtonTheme.of(context).textTheme作为textTheme属性的默认值。

最新更新