Flutter即时通讯插件mobile_chat_flutter的使用

Flutter即时通讯插件mobile_chat_flutter的使用

mobile_chat_flutter 插件可以帮助你在Flutter应用中管理客户关系,并通过聊天功能与客户进行交流。

安装

1. 预安装

a. 确保你的应用已经集成了 Firebase Cloud Messaging。 b. 在 mobile chat integration page 中创建移动聊天渠道集成,并确保完成以下步骤:

  • 添加应用包名或bundle ID。
  • 填写来自Firebase控制台的服务密钥(项目设置 -> 服务账号 -> 生成新的私有密钥)。

2. 安装 Mobile Chat Flutter

pubspec.yaml 文件中添加依赖:

dependencies:
  mobile_chat_flutter: $latestSdkVersion

3. 添加权限

iOS项目中的 Info.plist
  1. Runner -> Info.plist 文件中添加 NSMicrophoneUsageDescriptionNSCameraUsageDescription
  2. 添加以下内容到 Runner -> Info.plist 文件:
  <key>LSSupportsOpeningDocumentsInPlace</key>
  <true/>
  <key>UIFileSharingEnabled</key>
  <true/>
iOS项目的 Podfile

Podfile 中添加以下内容:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        'PERMISSION_CAMERA=1',
        'PERMISSION_MICROPHONE=1',
        'PERMISSION_PHOTOS=1',
      ]
    end
  end
end
Android项目的 AndroidManifest.xml

添加以下权限:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />

同时,添加以下内容:

<provider
    android:name="com.pichillilorenzo.flutter_inappwebview_android.InAppWebViewFileProvider"
    android:authorities="${applicationId}.flutter_inappwebview_android.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

使用

初始化

在每个使用 Mobile Chat Flutter 函数的 Dart 文件中添加以下导入:

import 'package:mobile_chat_flutter/mobile_chat_flutter.dart';

实现初始化函数,尽早将其引入你的应用中:

MobileChatInitialization.init(
    appId: string, 
    clientId: string, 
    secretKey: string, 
    externalId: string, 
    fullName: string
) : string

参数 appId, clientId, secretKey 可以在集成页面中找到。externalId 是客户的唯一标识符,fullName 是客户的全名。

示例初始化代码:

// 处理登录成功的函数
onLoginSuccessful(UserInfo userInfo) {
  //...
  MobileChatInitialization.init(
    "YOUR_APP_ID",
    "YOUR_CLIENT_ID",
    "YOUR_SECRET_KEY",
    "${userInfo.id}",
    "${userInfo.fullName}",
  );
  //...
}

聊天功能

MobileChatScreen 用于客户与代理进行聊天。

@override
Widget build(BuildContext context) {
  return MaterialApp(
        title: 'Your app title',
        onGenerateRoute: (settings) {
          final argument = settings.arguments;
          switch (settings.name) {
            case 'route-key-to-mobile-chat-screen':
              return MaterialPageRoute(
                builder: (_) => const MobileChatScreen(),
              );
          }
        }
  );
}

// 导航到移动聊天屏幕
navigator.pushNamed(context, 'route-key-to-mobile-chat-screen');

通知功能

注册客户的FCM令牌到移动聊天服务器以接收来自代理的通知:

registerMobileChatNotification(fcmToken: string) : string

为了区分移动聊天的有效负载和你自己的有效负载,可以使用以下函数:

isMobileChatPayload() : boolean

获取移动聊天组件是否已打开的状态:

isMobileChatOpened() : boolean

当用户从应用中登出时,可以停止接收通知,实现以下函数:

revokeNotification() : string

示例通知功能实现:

// 注册你的FCM令牌到移动聊天
FirebaseMessaging.instance.getToken().then((fcmToken) async {
    await MobileChatNotification.registerNotification(fcmToken ?? "");
});

// 处理来自移动聊天的通知
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
    if (MobileChatNotification.isMobileChatPayload(remoteMessage.toMap())) {
      if (!MobileChatNotification.isMobileChatOpened()) {
        // 处理移动聊天通知

      }
    } else {
      // 处理你自己的通知
    }
});

更多关于Flutter即时通讯插件mobile_chat_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter即时通讯插件mobile_chat_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


mobile_chat_flutter 是一个用于在 Flutter 应用中实现即时通讯功能的插件。它可以帮助开发者快速集成聊天功能,支持文本、图片、语音等多种消息类型。

以下是使用 mobile_chat_flutter 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  mobile_chat_flutter: ^版本号

请将 ^版本号 替换为最新的插件版本号。

2. 初始化插件

main.dart 文件中初始化 mobile_chat_flutter 插件。通常需要在应用的 main 函数中进行初始化:

import 'package:mobile_chat_flutter/mobile_chat_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileChatFlutter.initialize(
    appId: '你的AppID',
    appKey: '你的AppKey',
  );
  runApp(MyApp());
}

appIdappKey 需要从你的即时通讯服务提供商处获取。

3. 登录用户

在用户登录时,使用 MobileChatFlutter 提供的登录方法:

await MobileChatFlutter.login(userId: '用户ID', token: '用户Token');

userId 是用户的唯一标识符,token 是用户的身份验证令牌。

4. 创建聊天界面

使用 ChatView 组件来创建聊天界面:

import 'package:mobile_chat_flutter/mobile_chat_flutter.dart';

class ChatScreen extends StatelessWidget {
  final String targetUserId;

  ChatScreen({required this.targetUserId});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('聊天'),
      ),
      body: ChatView(
        targetUserId: targetUserId,
      ),
    );
  }
}

targetUserId 是聊天对方的用户ID。

5. 发送消息

ChatView 组件通常内置了消息发送功能。如果需要自定义发送消息的逻辑,可以使用 MobileChatFlutter.sendMessage 方法:

await MobileChatFlutter.sendMessage(
  targetUserId: '对方用户ID',
  messageType: 'text', // 消息类型:text, image, audio 等
  content: '消息内容',
);

6. 接收消息

ChatView 组件会自动处理消息的接收和显示。如果需要自定义消息接收逻辑,可以监听消息事件:

MobileChatFlutter.onMessageReceived.listen((message) {
  // 处理接收到的消息
  print('收到消息: $message');
});

7. 注销用户

当用户退出应用时,调用注销方法:

await MobileChatFlutter.logout();

8. 其他功能

mobile_chat_flutter 插件还提供了其他功能,如消息撤回、消息删除、群组聊天等。具体使用方法可以参考插件的官方文档或示例代码。

示例代码

以下是一个简单的完整示例:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileChatFlutter.initialize(
    appId: '你的AppID',
    appKey: '你的AppKey',
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(targetUserId: '对方用户ID'),
    );
  }
}

class ChatScreen extends StatelessWidget {
  final String targetUserId;

  ChatScreen({required this.targetUserId});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('聊天'),
      ),
      body: ChatView(
        targetUserId: targetUserId,
      ),
    );
  }
}
回到顶部