Ravin Laheri
Ravin Laheri

Reputation: 822

Multiple textstyles in Textfield in Flutter

In my app, users can write in English as well as Arabic. So for English, I want to use "Poppins" as font style, and for Arabic, I want to use "sfArabic". I did not find any proper solution for that.

Below is my expected output -

enter image description here

Upvotes: 0

Views: 41

Answers (1)

Ahmed Wafik
Ahmed Wafik

Reputation: 216

You can customize style of any text in TextField by extending TextEditingController and override buildTextSpan method.

Check the code below:-

import 'package:flutter/material.dart';

class MultiStyleTextEditingController extends TextEditingController {
  
  bool isEnglishWord(String input) =>
      RegExp(r'^[A-Za-z][A-Za-z0-9]*$').hasMatch(input);

  bool isArabicWord(String input) => RegExp(r"^[ء-ي]+$").hasMatch(input);

  @override
  TextSpan buildTextSpan(
      {required BuildContext context,
      TextStyle? style,
      required bool withComposing}) {
    final words = text.split('');

    var textStyle = const TextStyle();

    final textSpanChildren = <TextSpan>[];
    for (var word in words) {
      if (isEnglishWord(word)) {
        textStyle =
            textStyle.copyWith(color: Colors.black, fontFamily: 'Poppins');
      } else if (isArabicWord(word)) {
        textStyle =
            textStyle.copyWith(color: Colors.red, fontFamily: 'sfArabic');
      }
      final TextStyle newTextStyle = style?.merge(textStyle) ?? textStyle;

      final child = TextSpan(
        text: word,
        style: newTextStyle,
      );
      textSpanChildren.add(child);
    }
    return TextSpan(
      style: style,
      children: textSpanChildren,
    );
  }
}

The result

Upvotes: 1

Related Questions