Harsh Rajpara
Harsh Rajpara

Reputation: 79

How to set text in the center of the container in Flutter when trying to reduce container size?

when text container size decrease with font size that time the text not set in center. it is gone below size of container how to solve it.

  Container(
              height: height,
              width: width,
              alignment: Alignment.center,
              decoration: _isSelected
                  ? BoxDecoration(
                color: Colors.transparent,
                border: Border.all(
                  width: 2,
                  color: Colors.black,
                ),
              )
                  : null,

              child: Align(
                alignment: Alignment.center,
                child: Text(
                  _displayText.isEmpty ? 'Enter Text' : _displayText,
                  textAlign: TextAlign.center,
                  overflow: TextOverflow.visible,
                  maxLines: 1,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: fontSize,
                  ),
                ),
              ),
            ),

this is image of output

Upvotes: 1

Views: 74

Answers (2)

Jahan Zaib
Jahan Zaib

Reputation: 1

Try it with the help of Center() like below:

Container(
          padding: EdgeInsets.all(8.0),
          decoration: _isSelected
              ? BoxDecoration(
            color: Colors.transparent,
            border: Border.all(
              width: 2,
              color: Colors.black,
            ),
          )
              : null,

          child: Center(
            child: Text(
              _displayText.isEmpty ? 'Enter Text' : _displayText,
              textAlign: TextAlign.center,
              overflow: TextOverflow.visible,
              maxLines: 1,
              style: TextStyle(
                color: Colors.black,
                fontSize: fontSize,
              ),
            ),
          ),
        ),

Upvotes: 0

Hassan
Hassan

Reputation: 656

Use the FittedBox widget to automatically scale the text to fit within the container while keeping it centred.

Container(
  height: height,
  width: width,
  alignment: Alignment.center,
  decoration: _isSelected
      ? BoxDecoration(
          color: Colors.transparent,
          border: Border.all(
            width: 2,
            color: Colors.black,
          ),
        )
      : null,
  child: FittedBox(
    fit: BoxFit.scaleDown, // Scale down the text to fit within the container
    alignment: Alignment.center,
    child: Text(
      _displayText.isEmpty ? 'Enter Text' : _displayText,
      textAlign: TextAlign.center,
      style: TextStyle(
        color: Colors.black,
        fontSize: fontSize,
      ),
    ),
  ),
),

Upvotes: 3

Related Questions