RichText Flutter

18-Sep-2024

Learn how to use RichText to style individual parts of your text in Flutter

Rich text widgets are used to display text in multiple styles within the same text area.
This way you can create different styles.
Apply different fonts, sizes, colors, etc. to different parts of the text.
The RichText widget uses a list of TextSpan widgets. Each TextSpan represents a piece of  text with a particular style.




import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
body: MyApp(),
),
)
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return
Center(
child: Container(
width: 500,
height: 100,
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
child:RichText(
text:TextSpan(
text: "Micro",
style: DefaultTextStyle.of(context).style,
children: const [
TextSpan(
text: " Tutorial",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
fontSize: 20
)
),
TextSpan(
text: " Flutter",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 20
)
)
]
),
)

),
);
}
}



In this example, the text is divided into three parts, each with its own style.
The first part is standard style, the second part is bold and blue, and the third part is italic and red.


Open Device Manager, run the emulator, and  then run the application. Next, check the working output and check the output  you declared in your code.


Output:


Comments