Dart/Flutter中如何为星号字符串设置红色?Text组件样式问题
解决方案
你没法直接给字符串变量绑定样式——字符串本身只是纯文本,样式是Flutter文本组件的专属属性。要实现同一文本里部分内容样式不同,得用富文本组件,下面是两种实用的实现方式:
方式一:使用 Text.rich(推荐,更简洁)
Text.rich 可以直接组合多个 TextSpan,每个 TextSpan 能单独设置样式:
const Text.rich( TextSpan( children: [ // 红色的* TextSpan( text: '*', style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold, fontSize: 40, ), ), // 原有的Registar文本 TextSpan( text: ' Registar', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 40, ), ), ], ), )
方式二:使用 RichText
如果需要更灵活的文本布局控制,可选择 RichText:
const RichText( text: TextSpan( style: TextStyle( // 设置默认样式,子TextSpan会自动继承 color: Colors.black, fontWeight: FontWeight.bold, fontSize: 40, ), children: [ TextSpan( text: '*', style: TextStyle(color: Colors.red), // 单独覆盖颜色 ), TextSpan(text: ' Registar'), // 继承默认样式 ], ), )
如果一定要用字符串变量存储*,直接把变量放到TextSpan的text属性里即可:
final String asterisk = '*'; Text.rich( TextSpan( children: [ TextSpan( text: asterisk, // 使用定义好的变量 style: TextStyle(color: Colors.red, fontSize: 40, fontWeight: FontWeight.bold), ), const TextSpan( text: ' Registar', style: TextStyle(color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold), ), ], ), )
内容的提问来源于stack exchange,提问作者Rafael Reis
相关产品推荐
相关产品推荐

