isa türk
isa türk

Reputation: 747

Flutter how to center the child of a Container which has flexible constraints

I am trying to build a message box like the ones used in messenger apps(ex: Whatsapp).

Without trying to centralize the Text :

image

Container must be flexible on both height and width based on the lenght of the message(string) it contains.

This is my code for it

Container(
         constraints: BoxConstraints(minHeight: 40,maxHeight: 200,maxWidth: 300,minWidth: 40),
         decoration: BoxDecoration(
           borderRadius:  BorderRadius.circular(40),
         ),
         child: Padding(
           padding: const EdgeInsets.fromLTRB(15,0,15,0),
           child: new Text(msg,maxLines: null,),
         ),
    )

However whenever I try to center the text(including padding) Widget, Container is being forced to it's maximum constraints. These are some of the methods I tried

All of these methods result the same :

image

Is there any way to center the Text widget and do not manipulate the box constraint doing it ?

Upvotes: 7

Views: 3348

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 268254

Try this:

Container(
  constraints: BoxConstraints(minHeight: 40, maxHeight: 200, maxWidth: 360, minWidth: 40),
  decoration: BoxDecoration(color: Colors.grey, borderRadius: BorderRadius.circular(40)),
  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
  child: Column(
    mainAxisSize: MainAxisSize.min,
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
      Text("Very long message"),
    ],
  ),
);

enter image description here

Upvotes: 9

Related Questions