Irfan Ganatra
Irfan Ganatra

Reputation: 1346

how to set different colour of particular letters of a string in Text widget in flutter

I am trying to create a basic calculator where I have a string for inputs..

like user has inputed 79+93-27,

Here I want to set black colour for digits and red for operators...

this is my code to explain what I want

this is a part of my code , and I don't want to change any kind of variable types..

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  String inputstring = '79+93-27';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
            child: Text(
          inputstring,
          style: TextStyle(fontSize: 30),
        )),
      ),
    );
  }
}

Upvotes: 1

Views: 1023

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17900

You can use RegExp and RichText like this:

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  String inputstring = '79+93-27';

  @override
  Widget build(BuildContext context) {
    RegExp regExp = new RegExp(r'(\+|-|\*|\/|=|>|<|>=|<=|&|\||%|!|\^|\(|\))');
    
    List inputs = inputstring.replaceAll(regExp, '').split('').toList();

    return MaterialApp(
      home: Scaffold(
        body: Center(
            child: RichText(
            text: TextSpan(
                children: inputstring.characters
                    .map((e) => inputs.contains(e)
                        ? TextSpan(
                            text: e,
                            style: TextStyle(color: Colors.black),
                          )
                        : TextSpan(
                            text: e,
                            style: TextStyle(color: Colors.red),
                          ))
                    .toList()),
          ),
        ),
      ),
    );
  }
}

enter image description here

Upvotes: 2

Ozan Taskiran
Ozan Taskiran

Reputation: 3552

You can use the RichText widget with multiple TextSpans. See the example:

https://api.flutter.dev/flutter/widgets/RichText-class.html

Upvotes: 1

Related Questions