首页 > 解决方案 > Flutter:如何使用 ListView.builder 在聊天 UI 中从上到下显示信息

问题描述

我正在创建一个聊天 UI,并希望更新的消息显示相反的顺序。但是,我希望聊天文本从 UI 顶部而不是底部开始

消息顺序有效。如何让消息从 UI 顶部而不是底部显示

所以,基本上我希望消息在“我的聊天标题”下方开始

谢谢你的帮助

代码片段

Widget build(BuildContext context) {
     return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Flutter Facts"),
      ),
      body: Column(children: <Widget>[
        Container(
         margin: const EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 0),
         padding: const EdgeInsets.all(15.0),
         width: MediaQuery.of(context).copyWith().size.width ,
         decoration: BoxDecoration(border: Border.all(width:1),),
  
         child:Text('My chat')
        ),
        Flexible(
            child: ListView.builder(
              padding: EdgeInsets.all(8.0),
              reverse: true, //To keep the latest messages at the bottom
              itemBuilder: (_, int index) => _messages[index],
              itemCount: _messages.length,
            ),),
        Divider(height: 1.0),
        Container(
          decoration: new BoxDecoration(color: Theme.of(context).cardColor),
          child: _queryInputWidget(context),
        ),
      ]),
    );
  }

在此处输入图像描述

我尝试将反向设置为 false .. 这样可以正确定位文本,但现在较新的消息位于顶部。不维护的顺序(旧 -> 新)

在此处输入图像描述

标签: flutter

解决方案


reverse参数Listview.builder用于设置显示项目的位置(顶部或底部)。如果设置为true,项目将显示在底部而不是顶部。所以你只需要删除reverse: true.

将最新消息保留在底部

因为项目是相对于它们的索引显示的,所以无论reversetrue还是,都会在底部显示最新消息false。该reverse参数与列表中项目的顺序无关。如果消息没有排序,您可以按时间排序。

如果消息以相反的顺序显示,您可以执行以下操作:

_messages = _messaged.reversed.toList();

推荐阅读