首页 > 解决方案 > 如何更改 Flutter 中子树的文本颜色?

问题描述

我希望每个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')
    ],
  ),
),

问题是我想要的Text 1变成黑色和白色。Text 2

我认为使用DefaultTextStyle.merge我仍然可以使用Theme.of(context)得到 general TextTheme,仍然保持更改DefaultTextStyle但显然我错了。

更改子树文本颜色的正确方法是什么,同时能够访问原始的其余部分Theme

标签: flutterflutter-theme

解决方案


这里的问题是您正在覆盖style使用 this style: Theme.of(context).textTheme.title,它从您的应用程序的当前获取title样式。textThemeTheme

一种可能的解决方案是使用自定义样式但复制颜色属性,如下所示:

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

简单的方法就是不使用textThemefrom your 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')
            ],
          ),
        ),

更新

我找到了另一种可以使用的方法:

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

如果您不想使用Builder小部件,请Theme.of(context).copyWith 在父小部件上使用(您的无状态小部件/有状态小部件)。


推荐阅读