Search code examples
fluttertextfieldtextstyle

How to make different font size in one textfield


How to make different font size in one textfield? I want to make 1 text field but so that different characters on input have different font size/color/style etc. Expamle:

=> TextFieldForm - [ AA BBaS OKEY MAN**!**]


Solution

  • You can try buildTextSpan by overriding TextEditingController.

    class CustomFontSizeTextEditingController extends TextEditingController {
       
       CustomFontSizeTextEditingController();
    
       @override
       TextSpan buildTextSpan({
         required BuildContext context,
         TextStyle? style,
         required bool withComposing,
       }) {
     
       // This composing logic has been taken from super.buildTextSpan()
    
       final composingRegionOutOfRange = !value.isComposingRangeValid || !withComposing;
    
       if (composingRegionOutOfRange) {
      
              // TODO: Your Custom Logic to separate out text based on your pattern and add it as separate TextSpan. 
      
              return TextSpan(
                style: style,
                children: [
                  // TextSpan(text: text1),
                  // TextSpan(text: text2),
                ],
             );
       }
    
       final composingStyle = style?.merge(const TextStyle(decoration: TextDecoration.underline)) ?? const TextStyle(decoration: TextDecoration.underline);
       return TextSpan(
         style: style,
         children: <TextSpan>[
            TextSpan(text: value.composing.textBefore(value.text)),
            TextSpan(
                 style: composingStyle,
                 text: value.composing.textInside(value.text),
            ),
            TextSpan(text: value.composing.textAfter(value.text)),
         ],
        );
      }
    }
    

    Source: https://docs.flutter.dev/release/breaking-changes/buildtextspan-buildcontext