Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: ListView.builder ignores BoxContrainst of Container child. Always applies full parent width

Tags:

flutter

Building chat bubbles in a chat app. I am unable to control the width of ListView.builder's Container children. The child Containers always take the full width of the ListView.builders parent:
Expanded -> Container width.

What I'm trying to achieve: message bubble width as small as possible while still containing message text, but not larger than 75% of the screen width.

Ignore wrapping of text for this simplified example.

Where and why is the chatBubble getting this full screen width?

Super Simplified widget layout example:

@override
Widget build(BuildContext context) {
  return Container(
    height: safeHeight,
    child: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            itemCount: messages.length,
            itemBuilder: (ctx, i) => chatBubble(messages[i]),
          )
        ),
        Container(
          height: 50,
          child: TextField(/* stuff */),
        )
      ]
    )
  );
}

chatBubble(Message msg) {
  return Padding(
    padding: EdgeInsets.all(8.0),
    child: Container(
      color: Colors.lightBlue,
      child: Text(msg.text),
      constraints: BoxConstraints(
        maxWidth: screenWidth * 0.75,
      ),
    )
  )
}

RESULT: enter image description here

like image 994
Maksym Moros Avatar asked Sep 20 '25 17:09

Maksym Moros


1 Answers

By default all the widgets inside a ListView are expanded, but you can use other widget to keep your content wrapped. If you will have more data in your chatBubble you can use a Column or a Wrap widget as follows:

  chatBubble(Message msg) {
    return Wrap(
      children: [
       Padding(
        ...
        ),
       ],
    );
  }

But if you want to provide only one child in that section you can use an Align Widget, which lets you use an alignment property to decide how to align the child. In this case, try the next:

 chatBubble(Message msg) {
    return Align(
      alignment: Alignment.centerRight,
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: ...
      ),
    );
  }
like image 67
Luis Miguel Mantilla Avatar answered Sep 22 '25 11:09

Luis Miguel Mantilla