'How to include multiple fonts into single text

I have an Arabic text in a pdf file. When I copy the text into Text Widget it becomes weird characters. When I checked the pdf file properties I found that it uses HQPB1, HQPB2, HQPB3, HQPB4 fonts, so I imported all of these fonts to my pubsec.yaml file. The problem is that I can use only one of these 4 fonts at a time but the pdf file uses all of these 4 fonts simultaneously.

this is the original text from pdf

when I added HQPB1.ttf only

when I added HQPB2.ttf only

So I want to include all of these 4 fonts in a Text so that each individual font should be used when it is needed as pdf does.



Solution 1:[1]

RichText(
  text: TextSpan(
    children: <TextSpan>[
      TextSpan(text: 'Hello ', style: TextStyle(fontFamily: "Serif", fontSize: 30, color: Colors.black)),
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.blue, fontSize: 30)),
      TextSpan(text: ' world!', style: TextStyle(fontFamily: "Roboto", fontSize: 30, color: Colors.red)),
    ],
  ),
)

Output:

enter image description here

Solution 2:[2]

In order to have multiple styles on one Text widget you have to use RichText. RichText has a children[] so you can have custom TextStyle (which will use whatever font you want) for each TextSpan

Check it out here -> https://api.flutter.dev/flutter/widgets/RichText-class.html

Solution 3:[3]

const Text.rich(
      TextSpan(
        children: <TextSpan>[
          TextSpan(
            text: 'Hello ',
            style: TextStyle(
              fontFamily: "Serif",
              fontSize: 30,
              color: Colors.black,
            ),
          ),
          TextSpan(
            text: 'bold',
            style: TextStyle(
              fontFamily: "Arial",
              fontWeight: FontWeight.bold,
              color: Colors.blue,
              fontSize: 30,
            ),
          ),
          TextSpan(
            text: ' world!',
            style: TextStyle(
              fontFamily: "Roboto",
              fontSize: 30,
              color: Colors.red,
            ),
          ),
        ],
      ),
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CopsOnRoad
Solution 2 Marko Niciforovic
Solution 3 Sanju Bhatt