[Flutter package] 富文本便捷配置库

1,177 阅读1分钟

flutter_rich_text

初衷

我们在写App的时候,需要使用富文本,最近我有一个垃圾分类的app,就是用到了局部加粗的功能,直接使用TextSpan的话,代码会稍显啰嗦,恰逢最近咸鱼的同学新发布了关于富文本的文章,我也决定写一个富文本的库,方便大家定制富文本

用法

用这个库,可以通过两种方式创建富文本

1. 通过一个数组创建,每个元素是一段文字+对应样式

RichText(
    overflow: TextOverflow.ellipsis,
    text: richTextForStyledTexts([
      RichStyleText(
          'aaa',
          TextStyle(
            color: Colors.red,
            fontSize: 20,
          )),
      RichStyleText('bbb',
          TextStyle(color: Colors.grey, fontSize: 20, fontWeight: FontWeight.w900)),
      RichStyleText('ccc',
          TextStyle(color: Colors.blue, fontSize: 10, fontWeight: FontWeight.w500)),
      RichStyleText('ddd',
          TextStyle(color: Colors.grey, fontSize: 50, fontWeight: FontWeight.w900))
    ]))

其核心方法是richTextForStyledTexts,每一段文字,是一个RichStyleText实例

2. 传入整个字符串,再传入一个样式数组,每个样式数组定义某个范围的样式

RichText(
    overflow: TextOverflow.ellipsis,
    text: richTextForStyledRange(
        'aaabbbcccddd',
        TextStyle(
          color: Colors.black,
        ),
        [
          RichStyleRange.length(
              0,
              3,
              TextStyle(
                color: Colors.red,
                fontSize: 20,
              )),
          RichStyleRange.length(3, 3,
              TextStyle(color: Colors.grey, fontSize: 20, fontWeight: FontWeight.w900)),
          RichStyleRange.length(6, 3,
              TextStyle(color: Colors.blue, fontSize: 10, fontWeight: FontWeight.w500)),
          RichStyleRange.length(9, 3,
              TextStyle(color: Colors.grey, fontSize: 50, fontWeight: FontWeight.w900))
        ]))

其核心方法是richTextForStyledRange,需要传入完整文字,全局样式,需要个性化的局部的样式,局部样式使用RichStyleRange实例表示

效果

两种方式,都能达到同样的效果,就看在你代码里怎么使用方便了。