Flutter中如何为Text组件内的指定文本片段设置加粗效果
实现方案
原有字符串拼接的方式只能给整段Text设置统一样式,要实现同一段文本内部分内容加粗,直接使用Flutter内置的Text.rich组件拆分文本片段即可,不需要改动Column的现有布局逻辑。
修改要点:
- 将每个拼接生成的Text替换为
Text.rich,内部通过TextSpan拆分固定标签、动态数据两个部分 - 仅给固定标签的TextSpan设置
fontWeight: FontWeight.bold加粗样式 - 修正原代码中
Phone Number文本缺失的冒号,和指定的固定标签文本保持一致
修改后的完整代码如下:
Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text.rich( TextSpan( children: [ const TextSpan( text: "Tutor Description: \n", style: TextStyle(fontWeight: FontWeight.bold), ), TextSpan(text: tutorList[index].tutorDescription.toString()), ], ), ), Text.rich( TextSpan( children: [ const TextSpan( text: "Tutor Email: ", style: TextStyle(fontWeight: FontWeight.bold), ), TextSpan(text: tutorList[index].tutorEmail.toString()), ], ), ), Text.rich( TextSpan( children: [ const TextSpan( text: "Phone Number: ", style: TextStyle(fontWeight: FontWeight.bold), ), TextSpan(text: tutorList[index].tutorPhone.toString()), ], ), ), Text.rich( TextSpan( children: [ const TextSpan( text: "Date Register: ", style: TextStyle(fontWeight: FontWeight.bold), ), TextSpan( text: df.format( DateTime.parse(tutorList[index].tutorDatereg.toString()), ), ), ], ), ), Text.rich( TextSpan( children: [ const TextSpan( text: "Subject List: ", style: TextStyle(fontWeight: FontWeight.bold), ), TextSpan(text: tutorList[index].subjectsName.toString()), ], ), ), ], )
如果你已经在应用主题或者父组件给Text配置了全局默认样式(字体大小、颜色、行高),上述代码中的TextSpan会自动继承这些默认样式,不需要额外给动态内容部分重复配置样式属性。
内容的提问来源于stack exchange,提问作者Elbert Jn
相关产品推荐
相关产品推荐

