Flutter聊天功能增强插件chatify的使用
Flutter聊天功能增强插件Chatify的使用
Chatify 是一个为 Flutter 应用程序提供聊天屏幕和功能的插件。它允许用户发送文本消息、语音记录、图片,并支持自定义其他类型的消息(如视频)。该插件集成了 Firestore、Firebase Storage 和 Firebase Messaging,以实现实时更新、存储和通知。




功能特性
- 用户友好的聊天屏幕,界面类似于流行的即时通讯应用。
- 支持发送和接收文本消息、语音记录和图片。
- 可定制化支持其他消息类型(如视频),需要手动配置。
- 基于用户连接强度的用户建议。
- 音频消息和图片的缓存机制。
- 查看和下载图片到相册。
- 集成 Firebase 发送通知(需要配置 Firebase Messaging)。
- 基本的消息管理功能:删除、转发和回复消息。
依赖项
Chatify 依赖以下组件:
- Firestore:提供实时数据库功能,用于存储和检索用户数据及聊天消息。
- Firebase Storage:用于存储和检索音频记录、图片和其他媒体文件。
- Firebase Messaging:支持向用户发送推送通知(需要在应用程序中进行配置)。
安装
要将 Chatify 集成到您的 Flutter 应用程序中,请按照以下步骤操作:
-
在
pubspec.yaml
文件中添加以下依赖项:dependencies: Chatify: ^0.0.1
-
运行以下命令以安装包:
flutter pub get
-
在 Dart 文件中导入包:
import 'package:chatify/chatify.dart';
-
按照 Firebase 设置文档配置 Firebase 在您的应用程序中。
使用方法
初始化 Chatify
在使用 Chatify 功能之前,您需要通过适当的选项对其进行初始化。使用 init
方法来初始化聊天功能并提供所需选项:
ChatifyController.init(ChatifyOptions(
usersCollectionName: 'users',
userData: UserData(
id: 'id', // 必填
name: 'name', // 必填
clientNotificationId: 'clientNotificationId', // 可选
profileImage: 'profileImage', // 可选
uid: 'uid', // 可选
searchTerms: 'searchTerms', // 可选
),
chatBackground: 'assets/png/chat.png',
notificationKey: 'notificationKeyFromFirebase',
onUserClick: (user) {
Get.to(UserProfile(user: Account.fromJson(user.data)));
},
customMessages: [
MessageWidget(
key: 'reel',
builder: (ctx, msg) => ReelCard(message: msg, width: 300),
),
],
));
初始化字段说明
- usersCollectionName(必填):Firestore 中的用户数据集合名称。
- userData(必填):表示 Firestore 集合中用户数据的映射模型。在此示例中,使用了
UserData
类,其属性包括id
、name
、clientNotificationId
、profileImage
、searchTerms
和uid
。您需要根据您的 Firestore 用户数据模型提供适当的值。如果您的模型中有searchTerms
,可以指定以启用搜索功能。 - chatBackground:指定聊天背景图像。在此示例中,路径设置为
'assets/png/chat.png'
。您可以提供自己的图像资产路径或将其留空以不设置自定义背景。 - notificationKey:用于通过 Firebase Messaging 发送通知。在此示例中,值设置为
'notificationKeyFromFirebase'
。您需要在应用程序中配置 Firebase Messaging 并获取适当的通知密钥。如果您不想发送通知,可以将其留空。 - onUserClick:当点击用户头像时调用的回调函数。在此示例中,它使用 GetX 包中的
Get.to
方法导航到用户个人资料页面。您可以自定义此回调函数以执行您希望的操作。 - customMessages:允许您添加自定义消息类型到聊天中。在此示例中,添加了一个带有键
'reel'
的自定义消息小部件,并提供了一个返回ReelCard
小部件的构建器函数。您可以通过提供唯一的键和返回消息类型的构建器函数来添加自己的自定义消息类型。
通过为 ChatifyOptions
对象中的每个字段提供适当的值,您可以根据具体需求自定义和配置聊天功能。
实现最近聊天屏幕
要在您的 Flutter 应用程序中实现最近聊天屏幕,请遵循以下示例:
import 'package:flutter/material.dart';
import 'package:chatify/chatify.dart';
void main() {
ChatifyController.init(ChatifyOptions(
usersCollectionName: 'users',
userData: UserData(
id: 'id',
name: 'name',
clientNotificationId: 'clientNotificationId',
profileImage: 'profileImage',
uid: 'uid',
),
));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chat App',
home: ChatScreen(),
);
}
}
或者,您可以直接通过调用以下方法导航到最近聊天屏幕:
ChatifyController.showRecentChats(currentUser);
其他功能
Chatify 插件还提供了更多功能,例如手动发送消息、添加评分、流式读取消息计数等。
// 开始与用户聊天并将他们添加到最近的聊天列表中,使用 startChat 方法
ChatifyController.startChat(user);
// 手动发送消息
ChatifyController.sendTo(user, message, type);
// 向用户添加评分,使用 addScore 方法:
ChatifyController.addScore(value: 5, user: user);
// 获取未读消息计数的流,使用 unReadMessagesCount 方法:
Stream<int> unreadCountStream = ChatifyController.unReadMessagesCount(currentUser);
示例代码
以下是完整的示例代码,展示如何使用 Chatify 插件:
import 'package:example/config.dart';
import 'package:example/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:chatify/chatify.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await _initChat();
runApp(const MyApp());
}
_initChat() async {
await Chatify.init(
config: chatifyConfig,
currentUserId: _currentUser.id,
);
}
ChatifyUser _currentUser =
users.firstWhere((element) => element.id == 'karrar');
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Brightness _brightness = Brightness.light;
bool isLTR = true;
Color primary = Colors.deepPurple;
String? image;
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chatify Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: primary,
brightness: _brightness,
),
primaryColor: primary,
useMaterial3: true,
),
localizationsDelegates: [
GlobalCupertinoLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale("en", "US"),
Locale("ar", "IQ"),
],
locale: Locale(isLTR ? 'en' : 'ar'),
home: ChatifyWraper(
theme: ChatifyThemeData(
recentChatsBrightness: _brightness,
chatBrightness: _brightness,
primaryColor: primary,
backgroundImage: image,
),
child: Scaffold(
appBar: AppBar(
title: const Text('Chatify Demo'),
actions: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: StreamBuilder(
stream: Chatify.unreadMessagesCount,
builder: (context, snapshot) {
int count = 0;
if (snapshot.hasData) {
count = snapshot.data as int;
}
return Badge(
label: Text(
count.toString(),
style: const TextStyle(
color: Colors.white,
),
),
isLabelVisible: count > 0,
padding: EdgeInsets.symmetric(horizontal: 7),
largeSize: 20,
backgroundColor: Colors.red,
offset: Offset(-3, 3),
child: IconButton(
onPressed: () {
Chatify.openAllChats(context);
},
icon: const Icon(CupertinoIcons.chat_bubble_text),
),
);
},
),
),
],
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: ListView(
children: [
SizedBox(height: 20),
Center(child: Text('Select Current User')),
SizedBox(height: 10),
SizedBox(
width: double.maxFinite,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 10,
runSpacing: 10,
children: users
.map(
(e) => _UserButton(
user: e,
onChanged: () => setState(() {}),
),
)
.toList(),
),
),
SizedBox(height: 20),
_MainButton(
onPressed: () {
setState(() {
_brightness = _brightness == Brightness.dark
? Brightness.light
: Brightness.dark;
});
},
text: 'Change Brightness',
icon: CupertinoIcons.moon,
),
_MainButton(
onPressed: () {
setState(() {
isLTR = !isLTR;
});
},
text: 'Change Direction',
icon: Icons.language_outlined,
),
SizedBox(height: 20),
Wrap(
spacing: 10,
runSpacing: 10,
alignment: WrapAlignment.center,
children: Colors.primaries
.map(
(e) => _ColorButton(
onPressed: () {
setState(() {
primary = e;
});
},
color: e,
),
)
.toList(),
),
SizedBox(height: 20),
Wrap(
spacing: 10,
runSpacing: 10,
alignment: WrapAlignment.center,
children: List.generate(
4,
(i) => _ImageButton(
onPressed: () {
setState(() {
image = 'assets/chat_background/${i + 1}.jpg';
});
},
isSelected:
image == 'assets/chat_background/${i + 1}.jpg',
image: 'assets/chat_background/${i + 1}.jpg',
),
),),
],
),
),
),
),
);
}
}
class _MainButton extends StatelessWidget {
const _MainButton({
required this.onPressed,
required this.text,
this.icon,
});
final Function() onPressed;
final String text;
final IconData? icon;
[@override](/user/override)
Widget build(BuildContext context) {
return TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor:
Theme.of(context).colorScheme.secondary.withOpacity(0.1),
foregroundColor:
Theme.of(context).colorScheme.brightness == Brightness.dark
? Colors.white
: Colors.black,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) ...[
Icon(icon),
SizedBox(width: 10),
],
Text(text),
],
),
);
}
}
class _ColorButton extends StatelessWidget {
const _ColorButton({
required this.onPressed,
required this.color,
});
final Function() onPressed;
final Color color;
[@override](/user/override)
Widget build(BuildContext context) {
return TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor: color,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
minimumSize: Size.square(50),
),
child: Icon(
Icons.check,
color: Theme.of(context).primaryColor == color
? Colors.white
: Colors.transparent,
),
);
}
}
class _ImageButton extends StatelessWidget {
const _ImageButton({
required this.onPressed,
required this.image,
required this.isSelected,
});
final Function() onPressed;
final String image;
final bool isSelected;
[@override](/user/override)
Widget build(BuildContext context) {
return TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
fixedSize: Size(100, 200),
),
child: Stack(
children: [
Positioned.fill(
child: Image.asset(
image,
fit: BoxFit.cover,
),
),
Center(
child: Icon(
Icons.check,
color: isSelected ? Colors.black : Colors.transparent,
),
)
],
),
);
}
}
class _UserButton extends StatelessWidget {
const _UserButton({
required this.user,
required this.onChanged,
});
final ChatifyUser user;
final Function() onChanged;
[@override](/user/override)
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
_currentUser = user;
_initChat();
onChanged();
},
style: TextButton.styleFrom(
backgroundColor: _currentUser == user
? Theme.of(context).primaryColor
: Theme.of(context).colorScheme.secondary.withOpacity(0.1),
foregroundColor: _currentUser == user
? Colors.white
: Theme.of(context).colorScheme.brightness == Brightness.dark
? Colors.white
: Colors.black,
padding: EdgeInsetsDirectional.only(
start: 6,
end: 20,
top: 6,
bottom: 6,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.network(
user.profileImage!,
height: 50,
width: 50,
fit: BoxFit.cover,
),
),
SizedBox(width: 10),
Text(user.name),
],
),
);
}
}
更多关于Flutter聊天功能增强插件chatify的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter聊天功能增强插件chatify的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
chatify
是一个用于 Flutter 的聊天功能增强插件,它可以帮助开发者快速实现聊天界面、消息发送、接收、显示等功能。以下是如何使用 chatify
插件的基本步骤和示例代码。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 chatify
插件的依赖。
dependencies:
flutter:
sdk: flutter
chatify: ^latest_version
然后运行 flutter pub get
来安装依赖。
2. 基本使用
2.1 初始化 Chatify
在使用 chatify
之前,你需要初始化它。通常可以在 main.dart
中进行初始化。
import 'package:chatify/chatify.dart';
void main() {
// 初始化 Chatify
Chatify.initialize(
apiKey: 'your_api_key',
userId: 'current_user_id',
);
runApp(MyApp());
}
2.2 创建聊天界面
chatify
提供了一个 ChatScreen
组件,你可以直接使用它来展示聊天界面。
import 'package:flutter/material.dart';
import 'package:chatify/chatify.dart';
class ChatPage extends StatelessWidget {
final String chatId;
ChatPage({required this.chatId});
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat'),
),
body: ChatScreen(
chatId: chatId,
),
);
}
}
2.3 发送消息
chatify
提供了 ChatService
来发送消息。
import 'package:chatify/chatify.dart';
void sendMessage(String chatId, String message) async {
await ChatService.sendMessage(
chatId: chatId,
message: message,
);
}
2.4 接收消息
你可以通过 ChatService
来监听消息。
import 'package:chatify/chatify.dart';
void listenForMessages(String chatId) {
ChatService.messagesStream(chatId: chatId).listen((message) {
print('New message: ${message.text}');
});
}
3. 自定义主题
chatify
允许你自定义聊天界面的主题。
Chatify.setTheme(
ChatTheme(
primaryColor: Colors.blue,
secondaryColor: Colors.white,
textColor: Colors.black,
// 其他主题属性
),
);
4. 处理用户头像和名称
你可以通过 Chatify
的 UserService
来处理用户头像和名称。
import 'package:chatify/chatify.dart';
void setUserProfile(String userId, String name, String avatarUrl) async {
await UserService.setUserProfile(
userId: userId,
name: name,
avatarUrl: avatarUrl,
);
}
5. 其他功能
chatify
还提供了许多其他功能,如:
- 消息状态(已发送、已读等)
- 消息类型(文本、图片、文件等)
- 消息时间戳
- 聊天列表
你可以根据项目需求进一步探索和使用这些功能。
6. 示例代码
以下是一个完整的示例代码,展示了如何使用 chatify
创建一个简单的聊天应用。
import 'package:flutter/material.dart';
import 'package:chatify/chatify.dart';
void main() {
Chatify.initialize(
apiKey: 'your_api_key',
userId: 'current_user_id',
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chatify Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChatPage(chatId: 'chat_id_1'),
);
}
}
class ChatPage extends StatelessWidget {
final String chatId;
ChatPage({required this.chatId});
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat'),
),
body: ChatScreen(
chatId: chatId,
),
);
}
}