如何为字符串设置不同Font Weight,在Text Widget中呈现结构化问答
实现访谈内容的富文本展示方案
完全可行,借助Flutter的Text.rich或RichText组件,就能在单个Widget内实现问题粗体、回答常规的混合样式展示,具体实现步骤如下:
核心实现思路
- 解析JSON中的
biografia字段,按\n分割成独立的问答条目 - 对每条条目按第一个冒号拆分问题与回答(避免回答内容含冒号导致分割错误)
- 为问题部分设置粗体样式,回答部分用默认样式,将所有片段组合成
TextSpan列表 - 通过
Text.rich渲染组合后的富文本
代码示例
// 假设已从接口获取并解析出biografia字段 String interviewContent = "您的从业年限是多久?:我已经做开发8年了\n您最擅长的技术栈?:Flutter全栈和后端Go\n您对新手有什么建议?:多写多练,不要怕踩坑"; // 生成富文本所需的TextSpan列表 List<TextSpan> buildInterviewSpans() { List<TextSpan> spans = []; List<String> qaItems = interviewContent.split('\n'); for (String item in qaItems) { // 仅分割第一个冒号,保留回答内容里的冒号 int colonIndex = item.indexOf(':'); if (colonIndex != -1) { String question = item.substring(0, colonIndex + 1); String answer = item.substring(colonIndex + 1) + '\n'; spans.add(TextSpan( text: question, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16), )); spans.add(TextSpan( text: answer, style: TextStyle(fontWeight: FontWeight.normal, fontSize: 16), )); } else { // 处理格式异常的条目,直接原样显示 spans.add(TextSpan(text: '$item\n', style: TextStyle(fontSize: 16))); } } return spans; } // 在页面中使用 @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20), child: Text.rich( TextSpan(children: buildInterviewSpans()), ), ), ); }
注意事项
- 优先使用
indexOf定位第一个冒号,避免split(':')破坏回答内容里的冒号 - 增加异常处理,兼容格式不规范的条目(比如无冒号的内容)
- 可根据需求统一调整字体大小、行高、颜色等基础样式
内容的提问来源于stack exchange,提问作者SimpleCoder
相关产品推荐
相关产品推荐

