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:
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: ...
),
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With