I am trying to create simple container for messages but failing for such easy code,
simply I want a container that having text of message, but failing to given width of container with length of text, it occupies entire maximum width and I don't want to give fixed width..
here is my coding
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bubble Demo'),),
body: ListView.builder(
itemCount: 20,
itemBuilder: (context,index){
return Column(children: [
Align(
alignment: index%4==0?Alignment.centerRight:Alignment.centerLeft,
child: Container(
height: 40,
//width: 100,
child: Center(
//after applying this center, it occupies entire max width which i dont wont
child: Text(
'Here is the Message Number ' index.toString(),),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: index%4==0?Colors.blue:Colors.orangeAccent,
),
),
),
Divider(
indent: 50,
),
],);
}),
);
}
}
CodePudding user response:
The Center widget will force the parent to take full widget if unbound.. You can add padding to the text and remove the center widget to make it aligned vertically in the center and remove the height of the Container too.. That way the text can stay dynamically sized if it recieves bigger text
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bubble Demo'),),
body: ListView.builder(
itemCount: 20,
itemBuilder: (context,index){
return Column(children: [
Align(
alignment: index%4==0?Alignment.centerRight:Alignment.centerLeft,
child: Container(
padding:EdgeInsets.symmetric(horizontal: 10, vertical: 7),
child: Text(
'Here is the Message Number ' index.toString(),),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: index%4==0?Colors.blue:Colors.orangeAccent,
),
),
),
Divider(
indent: 50,
),
],);
}),
);
}
}
CodePudding user response:
If you want to keep the height constant you can use this solution.
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Bubble Demo'),
),
body: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return Column(
crossAxisAlignment: _rightAlignment(index) ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Container(
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: _rightAlignment(index) ? Colors.blue : Colors.orangeAccent,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Here is the Message Number $index',
),
],
),
),
const Divider(
indent: 50,
),
],
);
},
),
),
);
}
bool _rightAlignment(int index) {
return index % 4 == 0;
}
}