Flutter聊天列表构建插件flutter_chat_list_builder的使用

Flutter聊天列表构建插件flutter_chat_list_builder的使用

简介

flutter_chat_list_builder 是一个用于构建聊天消息列表的 Flutter 插件。该插件专注于实现聊天列表的滚动行为,例如加载历史消息或保持当前阅读位置不变。它不负责 UI 的样式(如气泡布局),开发者可以自由定义消息的显示方式。


特性

  • 支持从底部加载历史消息。
  • 当用户不在列表底部时,添加新消息不会自动滚动到最新消息。

聊天列表加载演示


开始使用

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_chat_list_builder: ^版本号

然后运行以下命令以安装依赖:

flutter pub get

2. 导入包

在需要使用的地方导入:

import 'package:flutter_chat_list_builder/flutter_chat_list_builder.dart';

使用示例

示例代码

以下是一个完整的聊天页面示例,展示如何使用 flutter_chat_list_builder 构建聊天列表。

class Message {
  final int ind;
  Message(this.ind);
  final String _text = generateWordPairs().take(1).first.asCamelCase;
  final bool isMeSend = Random().nextBool();

  String get text => ind.toString() + _text;
}

class ChatPage extends StatelessWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 创建聊天控制器
    ChatListController<Message> controller = ChatListController<Message>();

    return Scaffold(
      appBar: AppBar(
        title: const Text("Chat Page"),
      ),
      body: ChatListBuilder<Message>(
        // 加载历史消息的逻辑
        loadHistory: () async {
          return Future.delayed(const Duration(seconds: 2), () {
            return LoadHistoryResponse(
              isHasMore: true, // 是否还有更多历史消息
              data: List.generate(30, (index) => Message(index)), // 模拟加载的历史消息
            );
          });
        },
        // 加载时的背景颜色
        loadingBackgroundColor: Colors.white,
        // 消息项的构建器
        itemBuilder: (_, element) {
          if (element.isMeSend) {
            return Row(
              textDirection: TextDirection.rtl,
              children: [
                Container(
                  margin: const EdgeInsets.all(10),
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.green[400], // 我发送的消息颜色
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Text(element.text),
                )
              ],
            );
          } else {
            return Row(
              children: [
                Container(
                  margin: const EdgeInsets.all(10),
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.yellow[400], // 对方发送的消息颜色
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Text(element.text),
                )
              ],
            );
          }
        },
        // 聊天列表控制器
        controller: controller,
      ),
      // 底部按钮用于发送新消息
      persistentFooterButtons: [
        ElevatedButton(
          onPressed: () {
            controller.addNewMessage(Message(999)); // 添加一条新消息
          },
          child: const Text('New Message'),
        ),
      ],
    );
  }
}

关键功能详解

1. 加载历史消息

通过 loadHistory 回调函数实现历史消息的加载。每次调用时,返回一个包含历史消息的 LoadHistoryResponse 对象。

loadHistory: () async {
  return Future.delayed(const Duration(seconds: 2), () {
    return LoadHistoryResponse(
      isHasMore: true, // 是否还有更多历史消息
      data: List.generate(30, (index) => Message(index)), // 模拟加载的历史消息
    );
  });
},

2. 消息项构建

通过 itemBuilder 自定义每条消息的显示样式。这里根据消息的发送者(isMeSend)来决定消息的颜色和方向。

itemBuilder: (_, element) {
  if (element.isMeSend) {
    return Row(
      textDirection: TextDirection.rtl,
      children: [
        Container(
          margin: const EdgeInsets.all(10),
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.green[400],
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(element.text),
        )
      ],
    );
  } else {
    return Row(
      children: [
        Container(
          margin: const EdgeInsets.all(10),
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.yellow[400],
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(element.text),
        )
      ],
    );
  }
},

3. 添加新消息

通过 controller.addNewMessage() 方法向聊天列表中添加新消息。

ElevatedButton(
  onPressed: () {
    controller.addNewMessage(Message(999)); // 添加一条新消息
  },
  child: const Text('New Message'),
),

更多关于Flutter聊天列表构建插件flutter_chat_list_builder的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter聊天列表构建插件flutter_chat_list_builder的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_chat_list_builder 是一个用于构建聊天列表的 Flutter 插件,它可以帮助开发者快速实现聊天界面的消息列表。以下是如何使用 flutter_chat_list_builder 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_chat_list_builder 的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_chat_list_builder: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入包

在你的 Dart 文件中导入 flutter_chat_list_builder

import 'package:flutter_chat_list_builder/flutter_chat_list_builder.dart';

3. 使用 ChatListBuilder

ChatListBuilder 是一个 ListView.builder 的封装,专门用于构建聊天列表。你可以通过传递消息列表和消息项构建器来使用它。

class ChatScreen extends StatelessWidget {
  final List<ChatMessage> messages = [
    ChatMessage(text: "Hello!", isMe: true),
    ChatMessage(text: "Hi there!", isMe: false),
    // 添加更多消息
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat'),
      ),
      body: ChatListBuilder(
        messages: messages,
        itemBuilder: (context, index) {
          final message = messages[index];
          return ChatBubble(
            text: message.text,
            isMe: message.isMe,
          );
        },
      ),
    );
  }
}

class ChatMessage {
  final String text;
  final bool isMe;

  ChatMessage({required this.text, required this.isMe});
}

class ChatBubble extends StatelessWidget {
  final String text;
  final bool isMe;

  ChatBubble({required this.text, required this.isMe});

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
        padding: EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: isMe ? Colors.blue : Colors.grey[300],
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: Text(
          text,
          style: TextStyle(color: isMe ? Colors.white : Colors.black),
        ),
      ),
    );
  }
}

4. 自定义消息项

你可以通过 itemBuilder 参数自定义每个消息项的显示方式。在上面的例子中,我们使用 ChatBubble 来显示每条消息。

5. 处理滚动和加载更多

ChatListBuilder 还支持处理滚动事件和加载更多消息。你可以通过 onLoadMore 回调来实现加载更多消息的功能。

ChatListBuilder(
  messages: messages,
  itemBuilder: (context, index) {
    final message = messages[index];
    return ChatBubble(
      text: message.text,
      isMe: message.isMe,
    );
  },
  onLoadMore: () {
    // 加载更多消息的逻辑
  },
)
回到顶部