How to Style Partial Part on Text() Widget in Flutter

In this example, we are going to show how to format or style some specific partial parts only on the Text widget in Flutter. It is often needed to style some part with one style and some other part with another style. See the example:

Text.rich(
    TextSpan(
      style: TextStyle(color: Colors.redAccent), //apply style to all
      children: [
      TextSpan(text: 'This website is', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' to learn Flutter.', style: TextStyle(fontSize: 28))
    ]
  )
)

RichText(
  text: TextSpan(
      style: TextStyle(color: Colors.blue), //apply style to all
      children: [
        TextSpan(text: 'This is', style: TextStyle(fontWeight: FontWeight.bold)),
        TextSpan(text: ' FlutterCampus', style: TextStyle(fontSize: 25)),
        TextSpan(text: ' Learn Flutter.', style: TextStyle(fontStyle: FontStyle.italic))
      ]
    )
)

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Partial Style on Text"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
            padding: EdgeInsets.all(20),
             child: Column(
                children: [ 
                  RichText(
                    text: TextSpan(
                       style: TextStyle(color: Colors.blue), //apply style to all
                       children: [
                          TextSpan(text: 'This is', style: TextStyle(fontWeight: FontWeight.bold)),
                          TextSpan(text: ' FlutterCampus', style: TextStyle(fontSize: 25)),
                          TextSpan(text: ' Learn Flutter.', style: TextStyle(fontStyle: FontStyle.italic))
                       ]
                     )
                  ),

                  Text.rich(
                     TextSpan(
                       style: TextStyle(color: Colors.redAccent), //apply style to all
                       children: [
                        TextSpan(text: 'This website is', style: TextStyle(fontWeight: FontWeight.bold)),
                        TextSpan(text: ' to learn Flutter.', style: TextStyle(fontSize: 28))
                      ]
                    )
                  )

              ])
          )
    );
  } 
}

In this way, you can style text partially in Text() widget in the Flutter app.

No any Comments on this Article


Please Wait...