Home > database >  flutter : How to change the color of a single word in a sentence?
flutter : How to change the color of a single word in a sentence?

Time:11-29

This is My text I want to change color which is in single quotes and last id, This text is dynamic Its coming from API ->

Your query 'THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .' has been raised with ticket id: #0606c2a23d9e

I want to make like this enter image description here

How to make it like this

CodePudding user response:

you can use RichText widget for this purpose in which you can give different styling to different part of the text

RichText(
 text: TextSpan(
 text: 'Hello ',
 style: DefaultTextStyle.of(context).style,
 children: const <TextSpan>[
  TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
  TextSpan(text: ' world!'),
],
),
)

CodePudding user response:

Let's assume that we have a pattern with single quotes

Your query 'THIS IS TESTING SUBJECT TRYING TO EXPLORE HAHA .' has been raised with ticket id: #0606c2a23d9e

Let's split your task into subtasks:

First, specify the regex

final regex = RegExp('\'. \'');

Next, let's try to find our target value with regex (assume that we have it all the time to omit nullability case here)

final target = regex.stringMatch(string)!;

Next, replace the target in the original string with some placeholder

final placeholder = '{@}';
final updatedString = string.replaceAll(regex, placeholder);

Next, split updatedString into tokens

final tokens = updatedString.split(RegExp(' '));

Next, build our TextSpan's by tokens. If the token is a placeholder then we replace it with the target and needed style

final spans = tokens
    .map((e) => e == placeholder
        ? TextSpan(text: target   ' ', style: TextStyle(color: Colors.blue))
        : TextSpan(text: e   ' '))
    .toList();

And last, collect everything together

Text.rich(TextSpan(children: spans)))

Full code example

class Page extends StatelessWidget {
  final String string;

  const Page({Key? key, required this.string}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final regex = RegExp('\'. \'');
    const placeholder = '{@}';
    final target = regex.stringMatch(string)!;
    final updatedString = string.replaceAll(regex, placeholder);
    final tokens = updatedString.split(RegExp(' '));
    final spans = tokens
        .map((e) => e == placeholder
        ? TextSpan(text: target   ' ', style: const TextStyle(color: Colors.blue))
        : TextSpan(text: e   ' '))
        .toList();
    
    return Center(child: Text.rich(TextSpan(children: spans)));
  }
}

enter image description here

  • Related