我正在尝试开发一个聊天应用程序,并且试图在容器内显示文本消息,并根据消息的长度设置宽度。如何根据字符串的长度设置宽度? 使用listview.builder显示P.S消息,并且每个容器都有背景色。
ListView.builder(
padding: EdgeInsets.only(top: 8.0, left: 15.0, right: 15.0),
itemCount: messages.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(20.0),
margin: index % 2 == 0
? EdgeInsets.only(bottom: 5.0, right: 60.0)
: EdgeInsets.only(bottom: 5.0, left: 60.0),
decoration: index % 2 == 0
? BoxDecoration(
border: Border.all(
color: Colors.grey,
),
borderRadius: BorderRadius.all(
Radius.circular(30.0),
),
)
: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.all(
Radius.circular(30.0),
),
),
child: Text(
messages[index].text,
style: TextStyle(color: Colors.black),
),
);
},
),
答案 0 :(得分:2)
@override
Widget build(BuildContext context) {
final messages = [
'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
'This is a short message.',
'This is a relatively longer line of text.',
'Hi!'
];
return Scaffold(
body: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Flex(
direction: Axis.horizontal,
mainAxisAlignment: index % 2 == 0
? MainAxisAlignment.start
: MainAxisAlignment.end,
children: <Widget>[
Container(
padding: const EdgeInsets.all(20.0),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
decoration: index % 2 == 0
? BoxDecoration(
border: Border.all(
color: Colors.grey,
),
borderRadius: BorderRadius.all(
Radius.circular(30.0),
),
)
: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.all(
Radius.circular(30.0),
),
),
child: Text(messages[index],
style: TextStyle(color: Colors.black)),
),
],
),
);
},
),
);
}
答案 1 :(得分:1)
好吧,这是因为ListView
的子代总是被拉伸,我对您的代码进行了一些更改,首先使用Align
小部件根据索引向左或向右对齐,然后包装{{ 1}}和Container
,以免填满宽度。
UnconstrainedBox