Flutter中替换段落下划线并修改对应文本颜色的实现问题
Solution for Variable Underscore Replacement with Styled Answer in Flutter
Problem Analysis
Your current code uses replaceFirst to swap a single underscore, then replaceAll to remove remaining underscores. This fails when the API returns multiple underscores as a single placeholder, and it can't apply custom coloring to the answer text.
Fix Implementation
Use RichText to mix styled and unstyled text, and a regex to match one or more underscores as a single placeholder:
// Replace your existing Text widget with this logic Widget buildAnswerReplacedContent(BuildContext context) { bool shouldShowAnswer = widget.isChecked == true || widget.answer?.id == widget.choiceAnswer?.id; if (!shouldShowAnswer) { return ConvertLatex( content: widget.question?.content, maxLine: isShow != true ? 5 : 100, ); } String content = widget.question?.content ?? ''; String answerText = widget.question?.answers?[widget.index ?? 0].text?.trim() ?? ''; // Customize the answer text style here TextStyle answerStyle = const TextStyle(color: Colors.blueAccent, fontWeight: FontWeight.bold); // Regex to match one or more underscores (the placeholder) RegExp underscoreRegex = RegExp(r'_+'); Match? placeholderMatch = underscoreRegex.firstMatch(content); if (placeholderMatch == null) { // No placeholder found, return original content return Text(content); } // Split content into parts before, during, and after the placeholder String beforePlaceholder = content.substring(0, placeholderMatch.start); String afterPlaceholder = content.substring(placeholderMatch.end); return RichText( text: TextSpan( style: DefaultTextStyle.of(context).style, // Inherit default text style children: [ TextSpan(text: beforePlaceholder), TextSpan(text: answerText, style: answerStyle), TextSpan(text: afterPlaceholder), ], ), ); }
How to Use
Call this function in your build method instead of the original conditional Text/ConvertLatex widgets:
buildAnswerReplacedContent(context),
Key Improvements
- Uses regex
_+to match any number of consecutive underscores as a single placeholder - Uses
RichTextto apply custom styling (color, weight, etc.) to the inserted answer text - Preserves all other content in the original question text
- Handles cases where no placeholder exists gracefully
内容的提问来源于stack exchange,提问作者tdn
相关产品推荐
相关产品推荐

