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

Time:11-08

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),
        )),
      ),
    );
  }
}

CodePudding user response:

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

CodePudding user response:

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

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

  • Related