新建项目-2.png

官网地址

一个富文本 Text,可以显示多种样式的 text。

RichText 要传入 TextSpan 数组,每个 TextSpan 是一个独立的文本,可以定义自己的 Style:

RichText

  1. RichText({
  2. Key key,
  3. @required this.text, //显示的文字,必须传一般都是 TextSpan 格式的
  4. this.textAlign = TextAlign.start, //text对齐方式 left,right,center,justify,start,end
  5. this.textDirection, //文字方向 TextDirection.rtl TextDirection.ltr
  6. this.softWrap = true, //是否允许换行显示
  7. this.overflow = TextOverflow.clip, //文本的截断方式
  8. this.textScaleFactor = 1.0, //文字大小倍率系数
  9. this.maxLines, //最大显示行数
  10. this.locale,
  11. this.strutStyle, //使用的支撑风格
  12. this.textWidthBasis = TextWidthBasis.parent, //设置一段文字宽度的显示基础
  13. })

TextSpan

  1. const TextSpan({
  2. this.text, //文字
  3. this.children, //子 TextSpan
  4. TextStyle style, //风格设定
  5. this.recognizer, //手势识别器
  6. this.semanticsLabel, //给文本加上一个语义标签 没有实际用
  7. }) : super(style: style,);


实例

  1. Padding(
  2. padding: EdgeInsets.fromLTRB(10, 10, 10, 5),
  3. child: Text.rich(
  4. TextSpan(
  5. children: <TextSpan>[
  6. TextSpan(
  7. text: "¥",
  8. style: TextStyle(
  9. color: Colors.red,
  10. fontSize: 20,
  11. fontWeight: FontWeight.w600,
  12. ),
  13. ),
  14. TextSpan(
  15. text: "9.8",
  16. style: TextStyle(
  17. color: Colors.blue,
  18. fontSize: 30,
  19. fontWeight: FontWeight.w300,
  20. )
  21. ),
  22. TextSpan(
  23. text: "998",
  24. style: TextStyle(
  25. color: Colors.grey,
  26. fontSize: 20,
  27. decoration: TextDecoration.lineThrough,
  28. )
  29. ),
  30. TextSpan(
  31. text: "不要998不要998不要998,只要9.8只要9.8,快来抢购呀!!!!"
  32. ),
  33. ],
  34. ),
  35. ),
  36. ),
  37. Padding(
  38. padding: EdgeInsets.fromLTRB(15, 15, 15, 15),
  39. child: RichText(
  40. text: TextSpan(
  41. children: <TextSpan>[
  42. TextSpan(
  43. text: "点我抢购",
  44. style: TextStyle(
  45. fontSize: 25,
  46. color: Colors.red,
  47. decoration: TextDecoration.underline,
  48. ),
  49. recognizer: TapGestureRecognizer()//添加点击事件,只有当前段文字有效
  50. ..onTap = () {
  51. print("onTap");
  52. AlertDialog(
  53. title: Text("onTap"),
  54. content: Text("你点击了抢购哦!"),
  55. );
  56. }
  57. ..onTapCancel = () {
  58. print("onTapCancel");
  59. }
  60. ..onTapDown = (TapDownDetails detail) {
  61. print("onTapDown");
  62. }
  63. ..onTapUp = (TapUpDetails detail) {
  64. print("onTapUp");
  65. },
  66. ),
  67. TextSpan(
  68. text: "帅哥,美女们",
  69. style: TextStyle(
  70. fontSize: 25,
  71. color: Colors.lightGreen,
  72. ),
  73. ),
  74. ],
  75. ),
  76. ),
  77. ),

image.png