The Wayback Machine - https://web.archive.org/web/20240930182632/https://www.geeksforgeeks.org/richtext-widget-in-flutter/
Open In App

Flutter – RichText Widget

Last Updated : 06 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The RichText widget is used to display text that uses various different styles. The displayed text is described using a tree of TextSpan objects, each of which has its own associated style that is used for that subtree. Depending on the layout constraints the text might break across multiple lines or might all be displayed on the same line.

Constructors:

Syntax:

RichText(
{Key key,
@required InlineSpan text,
TextAlign textAlign: TextAlign.start, 
TextDirection textDirection, 
bool softWrap: true, 
TextOverflow overflow: 
TextOverflow.clip, 
double textScaleFactor: 1.0, 
int maxLines, 
Locale locale, 
StrutStyle strutStyle, 
TextWidthBasis textWidthBasis: TextWidthBasis.parent, 
TextHeightBehavior textHeightBehavior,

Properties:

  • children: The widgets below this widget in the tree.
  • hashCode: The hash code for this object.
  • key: Controls how one widget replaces another widget in the tree.
  • runtimeType: A representation of the runtime type of the object.
  • text: The text to display in this widget.
  • textAlign: How the text should be aligned horizontally.
  • local: This property takes in Locale class as the object. It controls the font used for the text depending on the language used.
  • maxLines: The maxLines property takes in an int value as the object. It controls the maximum number of lines that can be there for the text to expand and wrap.
  • overflow: TextOverflow enum is the object given to its class it controls the text in case of overflow.
  • softWrap: This property takes in a boolean value as the object. If it is set to false the gulphs in the text become wider.
  • textDirection: This property takes in TextDirection class as the object to decide the direction of the text. It can be either from left-to-right or right-to-left.
  • textHightBehaviour: TextHeightBehavior class is the object given to this property. It controls how the text will be highlighted.
  • textScaleFactor: This property is taken in a double value as the object to determine the relative size of the font.
  • textWidthBasis: TextWidthBasis enum is the object of this property. It controls the width of a single line of text being measured.

Example:

Dart




import 'package:flutter/material.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is
  //the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ClipOval',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePAGE(),
      debugShowCheckedModeBanner: false,
    );
  }
}
 
class MyHomePAGE extends StatefulWidget {
  const MyHomePAGE({Key? key}) : super(key: key);
 
  @override
  // ignore: library_private_types_in_public_api
  _MyHomePAGEState createState() => _MyHomePAGEState();
}
 
class _MyHomePAGEState extends State<MyHomePAGE> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GeeksforGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Center(
          child: RichText(
        // Controls visual overflow
        overflow: TextOverflow.clip,
 
        // Controls how the text should be aligned horizontally
        textAlign: TextAlign.end,
 
        // Control the text direction
        textDirection: TextDirection.rtl,
 
        // Whether the text should break at soft line breaks
        softWrap: true,
 
        // Maximum number of lines for the text to span
        maxLines: 1,
 
        // The number of font pixels for each logical pixel
        textScaleFactor: 1,
        text: TextSpan(
          text: 'Hello ',
          style: DefaultTextStyle.of(context).style,
          children: const <TextSpan>[
            TextSpan(
                text: 'Geeks', style: TextStyle(fontWeight: FontWeight.bold)),
          ],
        ),
      )),
      backgroundColor: Colors.lightBlue[50],
    );
  }
}
 
class MyClip extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) {
    return const Rect.fromLTWH(0, 0, 100, 100);
  }
 
  @override
  bool shouldReclip(oldClipper) {
    return false;
  }
}


Output:

Richtext in flutter

Output explanation:

  1. Create a stateless widget as the main widget of the app.
  2. Define a class representing the home screen using a stateful widget.
  3. Define the appbar inside a scaffold widget.
  4. Place the Richtext widget in the center.


Previous Article
Next Article

Similar Reads

Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Flutter - ColoredBox Class Widget
A Colored Box is a container that fills it with color according to its child or A widget that paints its area with a specified Color and then draws its child on top of that color. A sample image is given below to get an idea about what we are going to do in this article. How to use it? You can simple use this widget anywhere in your project as you
3 min read
How to Get the Height of a Widget in Flutter?
To get the height of a widget in Flutter, you can use the LayoutBuilder widget to obtain the constraints of the parent container and then get the height from those constraints. How to use it? You can simply use this widget anywhere in your project as you needed that. LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { doubl
3 min read
Difference Between Stateless and Stateful Widget in Flutter
As we all know the flutter app consists of widgets only, these are broadly classified into two types: Stateless WidgetStateful WidgetState: Before knowing the difference between the stateless and stateful widget we should take a look at the definition of State of a widget. The State is information that can read synchronously when the widget is buil
3 min read
Flutter - Wrap Widget
Wrap widget aligns the widgets in a horizontal and vertical manner. Generally, we use Rows and Columns to do that but if we have some widgets which are not able to fit in the Row/Column then it will give us Overflow Message ( for ex: Right Overflowed by 570 pixels). Constructor of Wrap class:Wrap({Key key, Axis direction, WrapAlignment alignment, d
3 min read
Raised Button widget in Flutter
RaisedButton is the material design button based on a Material widget that elevates when pressed upon in flutter. It is one of the most widely used buttons in the flutter library. Let's understand this button with the help of an example. Disclaimer: As of May 2021 the RaisedButton class in flutter is deprecated. ElevatedButton class should be used
5 min read
OffStage Widget in Flutter
Flutter provides an inbuilt widget called “Offstage”, which is been used to hide or show any widget programmatically depending on user action/event. Offstage Widget is a widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit-testing, and without taking any room in the paren
4 min read
NotificationListener Widget in Flutter
In Flutter, every Scrollable sends Notifications that contain information about the current scroll state. So to catch these notifications we use NotificationListener Widget. NotificationListener Widget will listen for Notifications bubbling up the tree. In this, article we will learn about NotificationListener Widget Default Constructor:Notificatio
4 min read
endDrawer Widget in Flutter
The endDrawer is the panel displayed to the side of the body (Scaffold Widget). It is generally hidden in mobile devices. We can open it by swiping in from right to left, or we can customise it to open on-press of an icon or a button. This widget is similar to the already present Drawer widget in flutter except for the fact the Drawer by default op
2 min read
Table Widget in Flutter
Table widget is used to display items in a table layout. There is no need to use Rows and Columns to create a table. If we have multiple rows with the same width of columns then Table widget is the right approach. SliverList or Column will be most suitable if we only want to have a single column. The height of rows in the Table widget is dependent
3 min read
PageView Widget in Flutter
The PageView widget allows the user to transition between different screens in their flutter application. All you need to set it up are a PageViewController and a PageView. Constructor of PageView class:Syntax: PageView({Key key, Axis scrollDirection, bool reverse, PageController controller, ScrollPhysics physics, bool pageSnapping, void Function(i
3 min read
ListWheelScrollView Widget in Flutter
ListWheelScrollView is a flutter widget that is used to build ListView with a 3D effect. We can also use ListView to create a list of items but we can't add a 3D effect to it plus it also comes with a constraint that all the children inside this widget must be of the same size along the strolling axis. Flutter's ListWheelScrollView adds its childre
7 min read
FlatButton Widget in Flutter
FlatButton is the material design widget in a flutter. It is a text label material widget that performs an action when the button is tapped. Let's understand with the help of examples. Disclaimer: As of May 2021 the FlatButton class in flutter is deprecated. TextButton class should be used instead. The later class will eventually be removed from fl
3 min read
ClipOval widget in Flutter
ClipOval widget clips the child widget in oval or circle shape. We can reshape the child widget by changing width and height. If width and height are equal the shape will be circular. If the width and height are given differently then the shape will be oval. Let's understand this with the help of an example. Constructor of ClipOval class:Syntax: Cl
2 min read
Center widget in Flutter
Center widget comes built-in with flutter, it aligns its child widget to the center of the available space on the screen. The size of this widget will be as big as possible if the widthFactor and heightFactor properties are set to null and the dimensions are constrained. And in case the dimensions are not constrained and the widthFactor and HeightF
2 min read
BottomNavigationBar Widget in Flutter
The BottonNavigationBar widget is used to show the bottom of an app. It can consist of multiple items such as icons, text, or both that leads to a different route depending upon the design of the application. It is meant to help the user navigate to different sections of the application in general. Constructors:Syntax: BottomNavigationBar( {Key key
4 min read
ClipRRect Widget in Flutter
The ClipRRect widget in flutter is used to clips its child using a rounded rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRect and is used to Clip a Rectangle portion of the child widget but with rounded corners Constructor:Syntax: C
2 min read
Drawer Widget in Flutter
Drawer widget is used to provide access to different destinations and functionalities provided in your application. It is represented by three horizontal parallel lines on the upper end of the scaffold. It has a horizontal movement from the edge of the Scaffold that navigates the link to different routes in the flutter app. In order to use the app
5 min read
ClipRect Widget in Flutter
The ClipRect widget is used to clips its child using a rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRRect and is used to Clip a Rectangle portion of the child widget but without the rounded corners Constructors:Syntax: ClipRect( {K
2 min read
Opacity Widget in Flutter
The Opacity widget that makes its child partially transparent. This class colors its child into an intermediate buffer and then merges the child back into the scene partially transparent. For values of opacity other than 0.0 and 1.0, this class is relatively expensive as it needs coloring the child into an intermediate buffer. For the value 0.0, th
2 min read
RotatedBox Widget in Flutter
The RotatedBox widget is used to rotate its child by an integral number of quarter turns. It is used to orient its child widgets into either horizontal or vertical orientation. Furthermore, it is very lightweight and can be used for designing various UI as it gives flexibility to the user over the Design of the app. Constructors:Syntax: RotatedBox(
2 min read
TextSpan Widget in Flutter
TextSpan is an immutable span of text. It has style property to give style to the text. It is also having children property to add more text to this widget and give style to the children. Let's understand this with the help of an example. Constructors:Syntax: TextSpan({String text, List<InlineSpan> children, TextStyle style, GestureRecognizer
3 min read
Flutter - Banner Widget
Banner widget comes built-in with flutter API. It is somewhat similar to the debug banner that we are used to seeing on the top-right corner on a flutter app in debug mode. It enables us to show a message or text on top of any other widget. Below we will see its implementation with the help of an example and all its properties. Constructor of Banne
3 min read
Align Widget in Flutter
Align Widget is the widget that is used to align its child within itself and optionally sizes itself based on the child's size. Align Widget is quite flexible and can change its size according to the size of its child. Constructor of Align class: Syntax: Align({Key key, AlignmentGeometry alignment: Alignment.center, double widthFactor, double heigh
2 min read
Flutter - Fading a Widget
Every application needs to navigate through multiple pages and components in an application. In flutter one way to do so is to make the use of routes (ie, pages). But when there is a need to just remove a part (element) from a page, using routes becomes redundant. This is where Fading comes in. In this, the component is simply faded away from the p
3 min read
Flutter - AnimatedContainer Widget
In Flutter a container is a simple widget with well-defined properties like height, width, and color, etc. The AnimatedContainer widget is a simple container widget with animations. These types of widgets can be animated by altering the values of their properties which are the same as the Container widget. These types of animation in Flutter is kno
3 min read
Flutter - AbsorbPointer Widget
AbsorbPointer is a built-in widget in flutter which absorbs pointer, in other words, it prevents its subtree from being clicked, tapped, scrolled, dragged, and responding to hover. In flutter, most widgets already come with an option to disable them for example in a RaisedButton we can set the onClicked function to null to disable, or we can use Ne
4 min read
Flutter - OctoImage Widget
The OctoImage widget in Flutter requires an ImageProvider to display images in an application. The images in the OctoImage widget can be supplied with a Progress indicator or a Place holder for loading the Image in it. An OctoImage widget makes use of the Octosets which are nothing but the combination of predefined placeholders, imagebuilder, and e
4 min read
Flutter - SliverAppBar Widget
SliverAppBar is a Material Design widget in flutter which gives scrollable or collapsible app-bar. The word Sliver is given to scrollable areas here. SliverAppBar basically gives us means to create an app-bar that can change appearance, blend in the background, or even disappear as we scroll. We already had AppBar widget in flutter which places the
7 min read
Flutter - Expanded Widget
Expanded widget in flutter comes in handy when we want a child widget or children widgets to take all the available space along the main-axis (for Row the main axis is horizontal & vertical for Column). Expanded widget can be taken as the child of Row, Column, and Flex. And in case if we don't want to give equal spaces to our children widgets w
5 min read
Article Tags :