mFe*_*ein 5 flutter flutter-theme
我希望每个Text特定的内部Widget都有白色,尽管它们都可以有不同的大小。我知道我可以将每个单曲更改Text为白色,但我想让它变得智能并更改该特定的主题Widget。
我试过这个:
DefaultTextStyle.merge(
style: TextStyle(color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Text 1',
style: Theme.of(context).textTheme.title,
),
Text('Text 2')
],
),
),
Run Code Online (Sandbox Code Playgroud)
问题是Text 1变成黑色,Text 2变成我想要的白色。
我认为使用DefaultTextStyle.merge我仍然能够使用Theme.of(context)来获得一般TextTheme,仍然保持更改DefaultTextStyle,但显然我错了。
更改子树文本颜色同时能够访问原始文本的其余部分的正确方法是什么Theme?
这里的问题是您正在style使用 this覆盖style: Theme.of(context).textTheme.title,它title从textTheme您的应用程序的当前位置获取样式Theme。
一种可能的解决方案是使用自定义样式但复制颜色属性,如下所示:
DefaultTextStyle(
style: TextStyle(color: Colors.white),
child: Builder(
builder: (context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Text 1',
style: Theme.of(context).textTheme.title.copyWith(
color: DefaultTextStyle.of(context).style.color),
),
Text('Text 2')
],
);
},
),
),
Run Code Online (Sandbox Code Playgroud)
最简单的方法就是不使用textTheme您的Theme,只需编写您自己的样式而不指定颜色,如下所示:
DefaultTextStyle(
style: TextStyle(color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Text 1',
//change the style without changing the color
style: TextStyle(fontSize: 40),
),
Text('Text 2')
],
),
),
Run Code Online (Sandbox Code Playgroud)
更新
我找到了您可以使用的另一种方法:
Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.apply(
bodyColor: Colors.white,
displayColor: Colors.white,
),
),
child: DefaultTextStyle(
style: TextStyle(color: Colors.white),
child: Builder(
builder: (context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Text 1',
style: Theme.of(context).textTheme.title,
),
Text('Text 2')
],
);
},
),
),
),
Run Code Online (Sandbox Code Playgroud)
如果您不想使用该小部件,请 在(无状态小部件/有状态小部件的)父小部件上Builder使用。Theme.of(context).copyWith
| 归档时间: |
|
| 查看次数: |
1868 次 |
| 最近记录: |