如何在 Flutter 的聊天气泡中实现时间文本换行行为
How to implement time text wrapping behaviour in chat bubble on Flutter
许多本地移动聊天信使,如电报、whatsapp 等,实现了这种换行行为:当没有足够的文本空间时,将时间标签换行。
简单的聊天气泡由两部分组成:文本和时间标签。在简单的情况下,它们几乎位于同一基线上。即使文本是多行的(最后一行的基线)。但在某些情况下,当没有空闲 space 并且文本试图相交时,会在气泡底部添加一个缩进。
如果我用图片和视频展示一下,就很容易理解了:
还有 2 个视频:
多行 https://youtu.be/eigLIHWaub8
单线https://youtu.be/9GMDFYwMqdU
如何在Flutter上实现?
您可以使用 Wrap
小部件执行非常相似的操作,但行为不完全相同:
Card(
color: Colors.greenAccent,
child: Wrap(
alignment: WrapAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Text message in multi-lines and it looks similar to what's in the picture "),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("10:0 PM"),
),
],
),
),
您可以在第一层使用假占位符作为时间(或其他信息),在第二层使用真实定位的文本。
class CustomCard extends StatelessWidget {
final String msg;
final String additionalInfo;
CustomCard({
@required this.msg,
this.additionalInfo = ""
});
@override
Widget build(BuildContext context) {
return Card(
child: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RichText(
text: TextSpan(
children: <TextSpan>[
//real message
TextSpan(
text: msg + " ",
style: Theme.of(context).textTheme.subtitle,
),
//fake additionalInfo as placeholder
TextSpan(
text: additionalInfo,
style: TextStyle(
color: Color.fromRGBO(255, 255, 255, 1)
)
),
],
),
),
),
//real additionalInfo
Positioned(
child: Text(
additionalInfo,
style: TextStyle(
fontSize: 12.0,
),
),
right: 8.0,
bottom: 4.0,
)
],
),
);
}
结果如下:
result screenshot
许多本地移动聊天信使,如电报、whatsapp 等,实现了这种换行行为:当没有足够的文本空间时,将时间标签换行。
简单的聊天气泡由两部分组成:文本和时间标签。在简单的情况下,它们几乎位于同一基线上。即使文本是多行的(最后一行的基线)。但在某些情况下,当没有空闲 space 并且文本试图相交时,会在气泡底部添加一个缩进。
如果我用图片和视频展示一下,就很容易理解了:
还有 2 个视频:
多行 https://youtu.be/eigLIHWaub8
单线https://youtu.be/9GMDFYwMqdU
如何在Flutter上实现?
您可以使用 Wrap
小部件执行非常相似的操作,但行为不完全相同:
Card(
color: Colors.greenAccent,
child: Wrap(
alignment: WrapAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Text message in multi-lines and it looks similar to what's in the picture "),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("10:0 PM"),
),
],
),
),
您可以在第一层使用假占位符作为时间(或其他信息),在第二层使用真实定位的文本。
class CustomCard extends StatelessWidget {
final String msg;
final String additionalInfo;
CustomCard({
@required this.msg,
this.additionalInfo = ""
});
@override
Widget build(BuildContext context) {
return Card(
child: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RichText(
text: TextSpan(
children: <TextSpan>[
//real message
TextSpan(
text: msg + " ",
style: Theme.of(context).textTheme.subtitle,
),
//fake additionalInfo as placeholder
TextSpan(
text: additionalInfo,
style: TextStyle(
color: Color.fromRGBO(255, 255, 255, 1)
)
),
],
),
),
),
//real additionalInfo
Positioned(
child: Text(
additionalInfo,
style: TextStyle(
fontSize: 12.0,
),
),
right: 8.0,
bottom: 4.0,
)
],
),
);
}
结果如下: result screenshot