Limit max width of Container in Flutter
You can add a constraint to the Container Widget with the preferred maxWidth
like this:
Widget build(context) {return Row( mainAxisSize: MainAxisSize.min, children: [ Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 200), padding: EdgeInsets.all(10), decoration: BoxDecoration( color: color ?? Colors.blue, borderRadius: BorderRadius.circular(10) ), child: msg ) ], );}
I hope this helps!
Use ConstrainedBox
with BoxConstraints
maxWidth
, wrapped in a Flexible()
widget. The Flexible widget allows for the box to resize for smaller screens as well.
Flexible( child: ConstrainedBox( constraints: BoxConstraints(maxWidth: 150), child: Container( color : Colors.blue, child: Text('Your Text here'), ), ),),
This required to be inside Row
or Column
Widget
1. Row
Row( children: [ Container( constraints: BoxConstraints(maxWidth: 300), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8.0)), child: Text("Long Text....") ), ], );
2. Column
Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( constraints: BoxConstraints(maxWidth: 300), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8.0)), child: Text("Long Text....") ), ], );
Here in both examples, it's working because Column
and Row
allow it's children to expand to it's given constraint/size.
Note: If a child wants a different size from its parent and the parent doesn’t have enough information to align it, then the child’s size might be ignored.