Flutter richtext center

Flutter RichText Center

In Flutter, RichText widget allows you to style the text differently within a single paragraph. By default, the text within a RichText widget is left-aligned. However, you can center the text by placing the RichText widget inside a Center widget.

Here’s an example of how you can use RichText and Center widgets together to center-align the text:

    
      Center(
        child: RichText(
          textAlign: TextAlign.center,
          text: TextSpan(
            text: 'Hello, ',
            style: TextStyle(
              color: Colors.black,
              fontSize: 18,
            ),
            children: [
              TextSpan(
                text: 'Flutter',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontStyle: FontStyle.italic,
                ),
              ),
              TextSpan(
                text: ' World!',
              ),
            ],
          ),
        ),
      )
    
  

In the above example, we have used the `Center` widget as the parent of `RichText`. The `textAlign` property of `RichText` is set to `TextAlign.center` to ensure the text is centered within the `RichText` widget.

The `text` property of `RichText` takes a `TextSpan` object, which allows you to define different styles for different portions of the text. In this case, we have defined three `TextSpan` objects to display the text “Hello,” in regular font, “Flutter” in bold and italic, and “World!” in regular font. You can modify these styles according to your requirements.

By wrapping the RichText widget with the Center widget, the text will be centered horizontally on the screen. You can also adjust the alignment vertically by using other alignment widgets like `Align` or `Container`.

Leave a comment