Flutter RichText TextSpan 打开链接的组件

10 min read

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都将应用RichTextstyle,即字体大小为18,颜色为红色。但是"OpenAI API key page"的颜色将会被其自己的样式覆盖,变为蓝色。