flutterdartflutter-textflutter-container

When resize the container text not stay in center in flutter


here when the drag the container the text is not center if some height and width get than container text set in center.

double width = 110.0;
double height = 40.0;
double fontSize = 14;
bool _isSelected = true;
child: Container(
    height: height,
    width: width,

    decoration: _isSelected ? BoxDecoration(
      color: Colors.transparent,
      border: Border.all(
        width: 2,
        color: Colors.black,
      ),
    ) : null,
  
    child: Center(
      child: TextField(
        key: textFieldKey,
        controller: textController,
        style: TextStyle(color: Colors.black, fontSize: fontSize),
        decoration: InputDecoration(
          fillColor: Colors.black,
            hintText: "Enter Your Text",
            helperStyle: TextStyle(color: Colors.black),
            border: InputBorder.none
        ),
        textAlign: TextAlign.center,
        onSubmitted: (text){
          setState(() {
            _isSelected = false;
          });
        },
    ),
  ),
),

This is drag icon functionality.

if(_isSelected)
  Positioned(
    top: top - ballDiameter / 2,
    left: left - ballDiameter / 2,
    child: ManipulatingBall(
      onDrag: (dx, dy) {
        var newWidth = width - (2*dx);
        var newHeight = height - (2*dx/aspectRatio);
        setState(() {
          fontSize = height / 3.57*1.5;
          print("height = $height");
          print("width = $width");
          print("fontsize = $fontSize");

          if(newHeight > 10 && newWidth > 10)
          {
            height = newHeight;
            width = newWidth;
            top = top + (dx/aspectRatio);
            left = left + dx;
          }

        });
      },
      handlerWidget: HandlerWidget.VERTICAL,
    ),
  ),

i add the image in this image text show on top of container not set center. here add image in below

what wrong in this code.


Solution

  • You can't expect the text inside TextField to stay centered if the Container's height is too small for the TextField. Here's an illustration:

    If I you put height: 20 to the Container, you will see this in the UI:

    enter image description here

    If you go to DevTools and enable guidelines, you'll notice this:

    enter image description here

    The TextField does not fit inside the Container, which make the text not centered.

    If you give enough height for the TextField, for example by giving height: 40 to the Container, you'll get this:

    enter image description here

    enter image description here

    It fits inside the Container, so it's now perfectly centered. You can try increasing the height and no matter how big the value is, the text will stay centered.


    To fix it, you can give a limit on the minimum value for the Container's height so that TextField will always fit.