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

时间:2019-08-12 04:25:11

标签: 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')
    ],
  ),
),

问题是Text 1变成了黑色,而Text 2是白色了。

我认为使用DefaultTextStyle.merge仍然可以使用Theme.of(context)来获得通用TextTheme,仍然保持对DefaultTextStyle的更改,但是显然我错了。

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

1 个答案:

答案 0 :(得分:2)

这里的问题是,您正在使用此style覆盖style: Theme.of(context).textTheme.title,它会从您当前title的{​​{1}}中获得textTheme样式您的应用。

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

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

如果您不想使用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') ], ); }, ), ), ), 小部件,请在父小部件(您的statelesswidget / statefulwidget的)上使用Builder

相关问题