You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Stack在Flutter容器内边距区域显示聊天消息时间?

问题分析

现有代码的核心问题是把时间文本嵌套在容器内部的Stack中,导致时间只能定位在消息内容区域的右下角,而非整个黄色容器的右下角,同时多余的嵌套Stack增加了不必要的层级。

代码修正

ListView.builder(
  itemCount: MyDummyData.messages.length,
  itemBuilder: (context, index) {
    final message1 = MyDummyData.messages[index]; // 补充原代码缺失的变量赋值
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Flexible(
          child: Stack(
            children: [
              Container(
                margin: const EdgeInsets.only(left: 100, bottom: 20),
                padding: const EdgeInsets.only(right: 50, top: 10, bottom: 10, left: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  color: Colors.yellow.shade200,
                ),
                child: Text(message1), // 移除内部嵌套Stack,直接放置消息文本
              ),
              // 将时间移到外层Stack,定位到黄色容器右下角
              Positioned(
                bottom: 20, // 匹配Container的margin.bottom,保证垂直位置对齐
                right: 10, // 与容器左padding呼应,可根据需求调整间距
                child: const Text('10:20'),
              ),
            ],
          ),
        ),
      ],
    );
  },
)

修改说明

  1. 移除容器内部的嵌套Stack,直接将消息文本作为Container的child,简化层级结构
  2. 将时间文本移到外层Stack中,与Container同级,通过Positioned精准定位到黄色容器的右下角
  3. 补充原代码缺失的message1变量赋值(否则会引发编译错误)
  4. 给EdgeInsets添加const修饰,优化组件性能

内容的提问来源于stack exchange,提问作者user22362195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:53:10