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

Flutter实现聊天应用左侧待接收消息加载动画,直至收到响应

Flutter聊天应用:对方消息位置显示加载指示器直到收到响应

实现思路

要在左侧(对方消息区域)显示加载动画,直到收到对方回复后隐藏,核心是用状态变量维护加载状态,结合列表项的条件判断动态渲染内容:

  • 用isLoading布尔变量控制加载状态:发送消息后设为true,收到对方响应后设为false并更新聊天记录_chatHistory
  • 在列表构建时,根据当前项的索引和isLoading状态,决定显示加载指示器还是消息文本

完整代码实现

ListView.builder(
  itemCount: _chatHistory.length,
  shrinkWrap: false,
  controller: _scrollController,
  padding: const EdgeInsets.symmetric(vertical: 16.0),
  physics: const BouncingScrollPhysics(),
  itemBuilder: (context, index) {
    final isSender = _chatHistory[index]["isSender"];
    final messageText = _chatHistory[index]["message"];
    final messageOwner = isSender ? MessageOwner.myself : MessageOwner.other;
    return MessageBubble(
      message: Message(owner: messageOwner, text: messageText),
      child: Container(
        padding: EdgeInsets.only(left: 14, right: 14, top: 10, bottom: 10),
        // 加载中且当前项不是最后一条消息时,显示加载指示器
        child: (index < _chatHistory.length - 1 && isLoading)
            ? CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
              )
            : Text(
                _chatHistory[index]["message"],
                style: TextStyle(
                  fontSize: 15,
                  color: isSender ? Colors.white : Colors.black,
                ),
              ),
      ),
    );
  },
),

注意事项

  • 加载状态切换时要调用setState()刷新UI,确保加载指示器及时显示/隐藏
  • 原代码的位置判断逻辑是index < _chatHistory.length -1,如果需要精准在「待接收消息的对方位置」显示加载,可以调整判断条件为index == _chatHistory.length -1 && isLoading && !isSender
  • 可根据UI风格自定义CircularProgressIndicator的颜色、大小等样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:25:16