如何根据其子Text的长度设置Container的宽度?扑 [英] How to set the width of a Container based on the length of its child Text? Flutter
本文介绍了如何根据其子Text的长度设置Container的宽度?扑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试开发一个聊天应用程序,并且试图在容器内显示文本消息,并根据消息的长度设置宽度.如何根据字符串的长度设置宽度?P.S消息是使用listview.builder显示的,每个容器都有背景色.
I am Trying to develop a chat app and I am trying to display the text messages inside a container and set the width according to the length of the message. How can I set the width according to the length of a String? P.S messages are displayed using listview.builder and each container has a background color.
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),
),
);
},
),
我想要什么:
推荐答案
@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)),
),
],
),
);
},
),
);
}
这篇关于如何根据其子Text的长度设置Container的宽度?扑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文