Flutter聊天流程管理插件flutter_chatflow的使用

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

Flutter聊天流程管理插件flutter_chatflow的使用

插件介绍

Flutter聊天流程管理插件flutter_chatflow是一个强大的、灵活的聊天解决方案,适用于Flutter应用程序。它提供了实时消息传递、私聊、群聊、自定义UI、用户管理、媒体共享、丰富的文本支持、用户打字事件监听等功能。

安装和使用示例

import 'package:flutter/material.dart';
import 'package:flutter_chatflow/chatflow.dart';
import 'package:flutter_chatflow/models.dart';
import 'package:flutter_chatflow/notifier.dart';
import 'package:flutter_chatflow/utils/types.dart';
import 'package:flutter_chatflow/widgets/image/image_upload_preview_with_text_input.dart';
import 'package:flutter_chatflow/widgets/media_selection_with_text.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatelessWidget {

  List<Message> _messages = [];
  ChatUser author = ChatUser({
    /// It should be unique and persistent for each user
    userID: 'randomID'
  })

  void _addMessage(Message message) {
    /// Handle sending message to server

    /// Sending to local collection below [OPTIONAL if sent to server and listened correctly]
    setState((){
      _messages.insert(0, message);
    });
  }

  void _handleSendPressed(String message, {Message? repliedTo}) {
    int createdAt = DateTime.now().millisecondsSinceEpoch;
    
    final textMessage = TextMessage(
      author: author,
      createdAt: createdAt,
      text: message,
      status: DeliveryStatus.sending
    );

    _addMessage(textMessage);
  }

  void _handleOnAttachmentPressed({Message? repliedTo}) async {
    /// Logic for adding image to chat.
    /// You could use a dialog to choose between different media types
    /// And rename the function accordingly
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Chat')),
      body: ChatFlow(
        messages: _messages,
        chatUser: author,
        onSendPressed: _handleSendPressed,
        onAttachmentPressed: _handleOnAttachmentPressed
      ),
    );
  }
}

示例代码解析

  1. 导入必要的包

    import 'package:flutter/material.dart';
    import 'package:flutter_chatflow/chatflow.dart';
    import 'package:flutter_chatflow/models.dart';
    import 'package:flutter_chatflow/notifier.dart';
    import 'package:flutter_chatflow/utils/types.dart';
    import 'package:flutter_chatflow/widgets/image/image_upload_preview_with_text_input.dart';
    import 'package:flutter_chatflow/widgets/media_selection_with_text.dart';
    
  2. 主函数

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

    这里创建了一个简单的的应用程序实例,并将其作为主入口点。

  3. 应用类

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: ChatScreen(),
        );
      }
    }
    

    创建一个MyApp类,其中包含一个home属性指向ChatScreen

  4. 聊天屏幕类

    class ChatScreen extends StatelessWidget {
    
      List<Message> _messages = [];
      ChatUser author = ChatUser({
        /// It should be unique and persistent for each user
        userID: 'randomID'
      })
    
      void _addMessage(Message message) {
        /// Handle send message to server
    
        /// Sending to local collection below [OPTIONAL if sent to server and listened correctly]
        setState((){
          _messages.insert(0, message);
        });
      }
    
      void _handleSendPressed(String message, {Message? repliedTo}) {
        int createdAt = DateTime.now().millisecondsSinceEpoch;
        
        final textMessage = TextMessage(
          author: author,
          createdAt: createdAt,
          text: message,
          status: DeliveryStatus.sending
        );
    
        _addMessage(textMessage);
      }
    
      void _handleOnAttachmentPressed({Message? repliedTo}) async {
        /// Logic for adding image to chat.
        /// You could use a dialog to choose between different media types
        /// And rename the function accordingly
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Chat')),
          body: ChatFlow(
            messages: _messages,
            chatUser: author,
            onSendPressed: _handleSendPressed,
            onAttachmentPressed: _handleOnAttachmentPressed
          ),
        );
      }
    }
    

    在这里定义了ChatScreen类,用于显示聊天界面。包括添加消息、发送消息、处理附件等逻辑。

  5. ChatFlow组件

    return ChatFlow(
      messages: _messages,
      chatUser: author,
      onSendPressed: _handleSendPressed,
      onAttachmentPressed: _handleOnAttachmentPressed
    ),
    

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

1 回复

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


当然,下面是一个关于如何使用 flutter_chatflow 插件来管理聊天流程的示例代码。这个插件假设已经安装并配置在你的 Flutter 项目中。

1. 安装 flutter_chatflow

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_chatflow 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_chatflow: ^最新版本号

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

2. 初始化聊天流程管理

在你的 Flutter 应用中,你需要初始化 ChatFlow 实例,并设置相关的参数。以下是一个简单的初始化示例:

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

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

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

class ChatFlowDemo extends StatefulWidget {
  @override
  _ChatFlowDemoState createState() => _ChatFlowDemoState();
}

class _ChatFlowDemoState extends State<ChatFlowDemo> {
  late ChatFlow chatFlow;

  @override
  void initState() {
    super.initState();
    // 初始化 ChatFlow
    chatFlow = ChatFlow(
      user: User(
        id: 'user123',
        name: 'John Doe',
        avatarUrl: 'https://example.com/avatar.png',
      ),
      onMessageSent: (message) {
        // 处理消息发送逻辑
        print('Message sent: $message');
      },
      onMessageReceived: (message) {
        // 处理消息接收逻辑
        print('Message received: $message');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ChatFlow Demo'),
      ),
      body: ChatScreen(chatFlow: chatFlow),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 发送示例消息
          chatFlow.sendMessage(
            text: 'Hello, how are you?',
            sender: chatFlow.user, // 这里假设是当前用户发送消息
          );
        },
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ),
    );
  }
}

class ChatScreen extends StatefulWidget {
  final ChatFlow chatFlow;

  ChatScreen({required this.chatFlow});

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  late List<Message> messages;

  @override
  void initState() {
    super.initState();
    messages = []; // 初始化消息列表
    // 监听消息更新
    widget.chatFlow.messageStream.listen((message) {
      setState(() {
        messages.add(message);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: messages.length,
      itemBuilder: (context, index) {
        final message = messages[index];
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                message.sender.name,
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
              Text(
                message.text,
                style: TextStyle(fontSize: 16),
              ),
            ],
          ),
        );
      },
    );
  }
}

class User {
  final String id;
  final String name;
  final String avatarUrl;

  User({required this.id, required this.name, required this.avatarUrl});
}

class Message {
  final User sender;
  final String text;

  Message({required this.sender, required this.text});
}

3. 功能说明

  • 初始化 ChatFlow:在 initState 方法中初始化 ChatFlow 实例,并设置用户信息和消息回调。
  • 发送消息:在 floatingActionButton 的点击事件中调用 chatFlow.sendMessage 方法发送消息。
  • 接收消息:通过监听 chatFlow.messageStream 来接收新消息,并更新消息列表。
  • 显示消息:在 ChatScreen 中使用 ListView.builder 来显示消息列表。

请注意,这只是一个简单的示例,实际应用中可能需要处理更多的细节,比如网络连接、消息状态(发送中、已发送、已读、未读)、用户认证等。flutter_chatflow 插件可能提供了更丰富的功能,具体可以参考其官方文档和示例代码。

回到顶部