在RichText
控件中,你可以使用DefaultTextStyle.of(context).style
来获取当前上下文的默认文字样式,并在此基础上为各个TextSpan
设置样式。
如果你想要为所有的TextSpan
设置统一的样式,你可以直接在RichText
中设置style
属性。但是请注意,这样设置的样式将会应用到所有的TextSpan
,包括那些自己定义了style
属性的TextSpan
。如果TextSpan
自己也定义了style
属性,那么它的样式将会覆盖RichText
的样式。
以下是一个例子:
RichText( text: TextSpan( style: DefaultTextStyle.of(context).style.copyWith(fontSize: 18, color: Colors.red), children: <TextSpan>[ TextSpan( text: 'OpenAI API key page', style: TextStyle(color: Colors.blue), recognizer: TapGestureRecognizer() ..onTap = () async { final url = 'https://platform.openai.com/account/api-keys'; if (await canLaunch(url)) { await launch(url); } else { throw '不能加载 $url'; } }, ), TextSpan(text: ' to create a new key and copy it.'), ], ), )
在这个例子中,所有的TextSpan
都将应用RichText
的style
,即字体大小为18,颜色为红色。但是"OpenAI API key page"的颜色将会被其自己的样式覆盖,变为蓝色。