Flutter Tutorials

Flutter app development tutorials


flutter – How to set Text background color

Flutter – Text Background Color

The Text widget displays a string of text with a single style in a flutter app. But depending on the layout constraints the string might break across multiple lines or might all be displayed on the same line. The style argument is optional in a Text instance. When the style argument is omitted, the text will use the style from the closest enclosing DefaultTextStyle. By default, the Text is not selectable. But flutter developers can make a Text selectable by wrapping a subtree with a SelectionArea widget.

The following flutter application development tutorial will demonstrate how we can set a background color for the Text. We will change the Text widget’s text default background color. Here we will assign a TextStyle object for the Text class style property value.

In the below flutter example code, we will use the TextStyle class backgroundColor property to set a background color for a Text widget’s text instead its default background color.

The TextStyle class represents an immutable style describing how to format and paint text.

The TextStyle class backgroundColor property value is a Color object which is the color to use as the background for the text. If the background property is specified, this backgroundColor property value must be null. The backgroundColor property is shorthand for background: Paint()..color = backgroundColor.

In the merge, apply, and lerp, conflicts between backgroundColor and background specification are resolved in the background’s property favor as example if the background property is specified in one place, it will dominate color in another place.

So finally, the flutter app developers can set a background color for the Text widget’s text using the Text class’s style property and TextStyle class’s backgroundColor property.

main.dart


import 'package:flutter/material.dart';

void main(){
  runApp(
      MaterialApp(
        home: Scaffold(
          appBar: AppBar(
              title: const Text("Flutter - Text Background Color")
          ),
          body: const Center(
              child: Text(
                "Lorem Ipsum is simply dummy text of the printing"
                    " and typesetting industry.",
                style: TextStyle(
                    fontSize: 25,
                    backgroundColor: Colors.black12,
                ),
                textAlign: TextAlign.center,
              )
          ),
        ),
      )
  );
}

More flutter tutorials



About Me

Flutter Developer

Design a site like this with WordPress.com
Get started