如何在 Flutter 中更改子树的文本颜色?

How to change the Text color for a subtree in Flutter?

我希望特定 Widget 中的每个 Text 都是白色,尽管它们都可以有不同的尺寸。我知道我可以将每个 singe 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) 来获得通用 TextTheme,仍然保持对 DefaultTextStyle 的更改,但显然我是错了。

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

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

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

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

简单的方法就是不使用 Theme 中的 textTheme,只需编写自己的样式而不指定颜色,如下所示:

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 小部件,请在父小部件(您的 statelesswidget/statefulwidget)上使用 Theme.of(context).copyWith