Flutter Text

 

A Text is a widget in Flutter that allows us to display a string of text with a single line in our application. Depending on the layout constraints, we can break the string across multiple lines or might all be displayed on the same line. If we do not specify any styling to the text widget, it will use the closest DefaultTextStyle class style. This class does not have any explicit style. In this article, we are going to learn how to use a Text widget and how to style it in our application.

Here is a simple example to understand this widget. This example shows our project's title in the application bar and a message in the application's body.

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() { runApp(MyApp()); }  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   @override  
  7.   Widget build(BuildContext context) {  
  8.     return MaterialApp(  
  9.         theme: ThemeData(  
  10.           primarySwatch: Colors.green,  
  11.         ),  
  12.         home: MyTextPage()  
  13.     );  
  14.   }  
  15. }  
  16. class MyTextPage extends StatelessWidget {  
  17.   @override  
  18.   Widget build(BuildContext context) {  
  19.     return Scaffold(  
  20.       appBar: AppBar(  
  21.           title:Text("Text Widget Example")  
  22.       ),  
  23.       body: Center(  
  24.           child:Text("Welcome to Javatpoint")  
  25.       ),  
  26.     );  
  27.   }  
  28. }  

In the above code, we have used a MaterialApp widget that calls the home screen using the MyTextPage() class. This class contains the scaffold widget, which has appBar and body where we have used the Text widget to display the title and body, respectively. It is a simple scenario of Text widget where we have to pass the string that we want to display on our page.



Abstract class in Java | Abstraction in Java

When we run this application in the emulator or device, we should get the UI similar to the below screenshot:

Flutter Text

Text Widget Constructor:

The text widget constructor used to make the custom look and feel of our text in Flutter:

  1. const Text(String data,{  
  2.     Key key,  
  3.     TextStyle style,  
  4.     StrutStyle strutStyle,  
  5.     TextAlign textAlign,  
  6.     TextDirection textDirection,  
  7.     TextOverflow overflow,  
  8.     bool softWrap,  
  9.     double textScaleFactor,  
  10.     int maxLines,  
  11.     String semanticsLabel,  
  12.     TextWidthBasis textWidthBasis,  
  13.     TextHeightBehavior textHeightBehavior  
  14.     }  
  15. )  

The following are the essential properties of the Text widget used in our application:

TextAlign: It is used to specify how our text is aligned horizontally. It also controls the text location.

TextDirection: It is used to determine how textAlign values control the layout of our text. Usually, we write text from left to right, but we can change it using this parameter.

Overflow: It is used to determine when the text will not fit in the available space. It means we have specified more text than the available space.

TextScaleFactor: It is used to determine the scaling to the text displayed by the Text widget. Suppose we have specified the text scale factor as 1.5, then our text will be 50 percent larger than the specified font size.

SoftWrap: It is used to determine whether or not to show all text widget content when there is not enough space available. If it is true, it will show all content. Otherwise, it will not show all content.

MaxLines: It is used to determine the maximum number of lines displayed in the text widget.

TextWidthBasis: It is used to control how the text width is defined.

TextHeightBehavior: It is used to control how the paragraph appears between the first line and descent of the last line.

Style: It is the most common property of this widget that allows developers to styling their text. It can do styling by specifying the foreground and background color, font size, font weight, letter and word spacing, locale, shadows, etc. See the table to understand it more easily:

AttributesDescriptions
foregroundIt determines the paint as a foreground for the text.
backgroundIt determines the paint as a background for the text.
fontWeightIt determines the thickness of the text.
fontSizeIt determines the size of the text.
fontFamilyIt is used to specify the typeface for the font. For this, we need to download a typeface file in our project, and then keep this file into the assets/font folder. Finally, config the pubspec.yaml file to use it in the project.
fontStyleIt is used to style the font either in bold or italic form.
ColorIt is used to determine the color of the text.
letterSpacingIt is used to determine the distance between the characters of the text.
wordSpacingIt is used to specify the distance between two words of the text.
shadowsIt is used to paint underneath the text.
decorationWe use this to decorate text using the three parameters: decoration, decorationColor, decorationStyle. The decoration determines the location, decorationColor specify the color, decorationStyle determine the shape.
  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() { runApp(MyApp()); }  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   @override  
  7.   Widget build(BuildContext context) {  
  8.     return MaterialApp(  
  9.         theme: ThemeData(  
  10.           primarySwatch: Colors.green,  
  11.         ),  
  12.         home: MyTextPage()  
  13.     );  
  14.   }  
  15. }  
  16. class MyTextPage extends StatelessWidget {  
  17.   @override  
  18.   Widget build(BuildContext context) {  
  19.     return Scaffold(  
  20.       appBar: AppBar(  
  21.           title:Text("Text Widget Example")  
  22.       ),  
  23.       body: Center(  
  24.           child:Text(  
  25.             "Hello World! This is a Text Widget.",  
  26.             style: TextStyle(  
  27.               fontSize: 35,  
  28.               color: Colors.purple,  
  29.               fontWeight: FontWeight.w700,  
  30.               fontStyle: FontStyle.italic,  
  31.               letterSpacing: 8,  
  32.               wordSpacing: 20,  
  33.               backgroundColor: Colors.yellow,  
  34.               shadows: [  
  35.                 Shadow(color: Colors.blueAccent, offset: Offset(2,1), blurRadius:10)  
  36.               ]  
  37.             ),  
  38.           )  
  39.       ),  
  40.     );  
  41.   }  
  42. }  

Output:

When we run this application in the emulator or device, we should get the UI similar to the below screenshot:

Flutter Text

Flutter RichText Widget

Sometimes we want to show a line or a paragraph with multiple styles such as bold, italicized, underlined, different color, different font or everything at once. In that case, we should have to use the RichText widget that allows us to perform multiple test styles without switching many widgets.

RichText is a very useful widget in Flutter, which is used for displaying a paragraph of text on the UI with multiple styles. Inside the widget, we can have different styles by giving it a tree of TextSpan widgets. Each TextSpan can set its own style for overriding the default style.

RichText Structure

The below image explains the structure of the RichText widget. In this image, the parent TextSpan has its own style property and a text parameter, and then it can contain several children TextSpan who have their own style property.

Flutter Text

From the above overview, now we will see how to use this widget in our application.

Example

Suppose our app has a login screen and an option to create a new user account. The creation of new user account section has a combination of regular text and colored text, as shown in the below screen:

Flutter Text

In the above image, we can see the text "Don't have an account? Sign up" is a single line text, where the last part is a clickable word that navigates the user on the sign-up page. To make this type of text, we will divide it into two parts. The first part uses the parent TextSpan and input the text "Don't have an account?" with the black color. The second part uses the children TextSpan and input the text "Sign up" with a blue color. See the below code:

  1. RichText(  
  2.     text: TextSpan(  
  3.         text: 'Don\'t have an account?',  
  4.         style: TextStyle(color: Colors.black, fontSize: 20),  
  5.         children: <TextSpan>[  
  6.             TextSpan(text: ' Sign up',  
  7.                 style: TextStyle(color: Colors.blueAccent, fontSize: 20)  
  8.             )  
  9.         ]  
  10.     ),  
  11. ),  

Since the "Sign up" is a clickable text, so we need to implement onTap() action on this part. The TextSpan contains TapGestureRecognizer() that implement onTap() action. In our example, we will use the recognizer property to make the text tappable. Let us show the entire code snippet to understand it more clearly.

Create a new project in the IDE you are using. Open the project, navigate to the lib folder, and replace the below code with the main.dart file.

  1. import 'package:flutter/material.dart';  
  2. import 'package:flutter/gestures.dart';  
  3.   
  4. void main() { runApp(MyApp()); }  
  5.   
  6. class MyApp extends StatelessWidget {  
  7.   @override  
  8.   Widget build(BuildContext context) {  
  9.     return MaterialApp(  
  10.         theme: ThemeData(  
  11.           primarySwatch: Colors.green,  
  12.         ),  
  13.         home: MyTextPage()  
  14.     );  
  15.   }  
  16. }  
  17. class MyTextPage extends StatelessWidget {  
  18.   @override  
  19.   Widget build(BuildContext context) {  
  20.     return Scaffold(  
  21.       appBar: AppBar(  
  22.           title:Text("Rich Text Widget Example")  
  23.       ),  
  24.       body: Container(  
  25.           child: Center(  
  26.             child: RichText(  
  27.               text: TextSpan(  
  28.                   text: 'Don\'t have an account?',  
  29.                   style: TextStyle(color: Colors.black, fontSize: 20),  
  30.                   children: <TextSpan>[  
  31.                     TextSpan(text: ' Sign up',  
  32.                         style: TextStyle(color: Colors.blueAccent, fontSize: 20),  
  33.                         recognizer: TapGestureRecognizer()  
  34.                           ..onTap = () {}  
  35.                     )  
  36.                   ]  
  37.               ),  
  38.             ),  
  39.           )  
  40.       )  
  41.     );  
  42.   }  
  43. }  

Output:

When we run this application in the emulator or device, we should get the UI similar to the below screenshot:

Flutter Text

How to show an icon in a text widget in Flutter?

Sometimes the developers need to show an icon with the text widget. To do this, Flutter provides a WidgetSpan() inside the RichText() widget to add an icon with the text widget. The below example explains it in a simple way:

  1. import 'package:flutter/material.dart';  
  2.   
  3. void main() { runApp(MyApp()); }  
  4.   
  5. class MyApp extends StatelessWidget {  
  6.   @override  
  7.   Widget build(BuildContext context) {  
  8.     return MaterialApp(  
  9.         home: MyTextPage()  
  10.     );  
  11.   }  
  12. }  
  13. class MyTextPage extends StatelessWidget {  
  14.   @override  
  15.   Widget build(BuildContext context) {  
  16.     return Scaffold(  
  17.       appBar: AppBar(  
  18.           title:Text("Rich Text Widget Example")  
  19.       ),  
  20.       body: Container(  
  21.           child: Center(  
  22.             child:RichText(  
  23.               text: TextSpan(  
  24.                 style: Theme.of(context).textTheme.body1,  
  25.                 children: [  
  26.                   TextSpan(text: 'Click ', style: TextStyle(fontSize: 25)),  
  27.                   WidgetSpan(  
  28.                     child: Padding(  
  29.                       padding: const EdgeInsets.symmetric(horizontal: 2.0),  
  30.                       child: Icon(Icons.add, color: Colors.red),  
  31.                     ),  
  32.                   ),  
  33.                   TextSpan(text: ' to add', style: TextStyle(fontSize: 25)),  
  34.                 ],  
  35.               ),  
  36.             )  
  37.           )  
  38.       )  
  39.     );  
  40.   }  
  41. }  

Output:

When we run this application in the emulator or device, we should get the UI similar to the below screenshot:

Flutter Text


Post a Comment

Previous Post Next Post