Flutter聊天列表展示插件chat_list的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter聊天列表展示插件chat_list的使用

chat_list 是一个用于在Flutter应用中快速集成聊天视图的插件,帮助你轻松启动聊天应用程序。本文将详细介绍如何使用该插件,并提供完整的示例代码。

示例

你可以查看 GitHub上的示例 获取更多细节。

示例截图

使用方法

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  chat_list: ^latest_version

然后运行 flutter pub get 来安装依赖。

2. 创建消息列表

创建一个包含消息的列表,每个消息都是一个 MessageWidgetMessage 对象。以下是一个简单的例子:

final List<Message> _messageList = [
  Message(
      content: "Hi, Bill! This is the simplest example ever.",
      ownerType: OwnerType.sender,
      ownerName: "Higor Lapa"),
  Message(
      content:
          "Let's make it better , Higor. Custom font size and text color",
      textColor: Colors.black38,
      fontSize: 18.0,
      ownerType: OwnerType.receiver,
      ownerName: "Bill Gates"),
  // 更多消息...
];

3. 使用 ChatList 组件

在你的 build 方法中使用 ChatList 组件来显示消息列表。你需要传递一个 ScrollController 来控制滚动行为。

import 'package:chat_list/chat_list.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ChatList Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'ChatList Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title = ""}) : super(key: key);
  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _scrollController = ScrollController();

  final List<Message> _messageList = [
    // 初始化消息列表
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: ChatList(
          children: _messageList,
          scrollController: _scrollController,
        )));
  }

  void _onNewMessage() {
    _scrollController.animateTo(_scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
  }
}

4. 完整示例

以下是完整的示例代码,包括如何初始化消息列表和处理新消息的滚动行为:

import 'package:chat_list/chat_list.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ChatList Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'ChatList Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title = ""}) : super(key: key);
  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _scrollController = ScrollController();

  final List<Message> _messageList = [
    Message(
        content: "Hi, Bill! This is the simplest example ever.",
        ownerType: OwnerType.sender,
        ownerName: "Higor Lapa"),
    Message(
        content:
            "Let's make it better , Higor. Custom font size and text color",
        textColor: Colors.black38,
        fontSize: 18.0,
        ownerType: OwnerType.receiver,
        ownerName: "Bill Gates"),
    Message(
        content: "Bill, we have to talk about business",
        fontSize: 12.0,
        ownerType: OwnerType.sender,
        ownerName: "Higor"),
    Message(
        content: "Wow, I like it. Tell me what I can do for you, pal.",
        ownerType: OwnerType.receiver,
        ownerName: "Bill Gates"),
    Message(
        content: "I'm just a copy",
        ownerType: OwnerType.sender,
        ownerName: "Higor"),
    Message(content: "Nice", ownerType: OwnerType.receiver, ownerName: "Bill Gates"),
    // 更多消息...
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: ChatList(
          children: _messageList,
          scrollController: _scrollController,
        )));
  }

  void _onNewMessage() {
    _scrollController.animateTo(_scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
  }
}

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

1 回复

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


当然,以下是如何在Flutter中使用chat_list插件来展示聊天列表的一个简单示例。请注意,这里假设你已经有一个Flutter开发环境,并且已经添加了chat_list插件到你的pubspec.yaml文件中。

首先,确保在你的pubspec.yaml文件中添加了chat_list依赖:

dependencies:
  flutter:
    sdk: flutter
  chat_list: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,我们编写一个示例应用来展示如何使用chat_list插件。

main.dart

import 'package:flutter/material.dart';
import 'package:chat_list/chat_list.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chat List Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChatListScreen(),
    );
  }
}

class ChatListScreen extends StatefulWidget {
  @override
  _ChatListScreenState createState() => _ChatListScreenState();
}

class _ChatListScreenState extends State<ChatListScreen> {
  // 示例聊天列表数据
  final List<Chat> chatList = [
    Chat(
      id: '1',
      avatarUrl: 'https://example.com/avatar1.jpg',
      name: 'Alice',
      lastMessage: 'Hello!',
      lastMessageTime: DateTime.now().subtract(Duration(minutes: 5)),
      unreadCount: 2,
    ),
    Chat(
      id: '2',
      avatarUrl: 'https://example.com/avatar2.jpg',
      name: 'Bob',
      lastMessage: 'How are you?',
      lastMessageTime: DateTime.now().subtract(Duration(hours: 1)),
      unreadCount: 0,
    ),
    // 可以添加更多聊天数据
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat List'),
      ),
      body: ChatList(
        chatList: chatList,
        onChatTapped: (Chat chat) {
          // 当点击聊天项时执行的回调
          print('Chat tapped: ${chat.name}');
          // 你可以在这里导航到聊天详情页面
        },
      ),
    );
  }
}

// Chat 数据模型
class Chat {
  final String id;
  final String avatarUrl;
  final String name;
  final String lastMessage;
  final DateTime lastMessageTime;
  final int unreadCount;

  Chat({
    required this.id,
    required this.avatarUrl,
    required this.name,
    required this.lastMessage,
    required this.lastMessageTime,
    required this.unreadCount,
  });
}

解释

  1. 依赖添加:确保在pubspec.yaml文件中添加了chat_list插件的依赖。

  2. 数据模型:定义了一个Chat数据模型,包含聊天的基本信息,如ID、头像URL、名称、最后一条消息、最后消息时间和未读消息数。

  3. UI构建

    • 使用MaterialAppScaffold构建了一个基本的Flutter应用结构。
    • 使用ChatList组件来展示聊天列表,并传入了一个chatList数据列表。
    • onChatTapped回调用于处理点击聊天项时的逻辑(在这个例子中,只是打印了被点击的聊天名称,但你可以在这里导航到聊天详情页面)。

请注意,上述代码示例中的ChatList组件和Chat数据模型是基于假设的chat_list插件API设计的。实际使用时,你需要参考chat_list插件的官方文档来调整代码,以确保与插件的实际API兼容。如果chat_list插件提供了不同的API或数据模型,请相应地修改代码。

回到顶部