Merge pull request #57 from Iconica-Development/1.4.0

1.4.0
This commit is contained in:
Gorter-dev 2024-03-27 14:37:10 +01:00 committed by GitHub
commit 169818e981
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 1016 additions and 256 deletions

View file

@ -1,3 +1,16 @@
## 1.4.0
- Add way to create group chats
- Update flutter_profile to 1.3.0
- Update flutter_image_picker to 1.0.5
## 1.3.1
- Added more options for styling the UI.
- Changed the way profile images are shown.
- Added an ontapUser in the chat.
- Changed the way the time is shown in the chat after a message.
- Added option to customize chat title and username chat message widget.
## 1.2.1 ## 1.2.1
- Fixed bug in the LocalChatService - Fixed bug in the LocalChatService

View file

@ -32,6 +32,14 @@ ios
.pub/ .pub/
/build/ /build/
# Platform-specific folders
**/android/
**/ios/
**/web/
**/windows/
**/macos/
**/linux/
# Symbolication related # Symbolication related
app.*.symbols app.*.symbols

View file

@ -4,6 +4,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_chat/flutter_chat.dart'; import 'package:flutter_chat/flutter_chat.dart';
import 'package:uuid/uuid.dart';
/// Navigates to the chat user story screen. /// Navigates to the chat user story screen.
/// ///
@ -31,6 +32,7 @@ Widget _chatScreenRoute(
BuildContext context, BuildContext context,
) => ) =>
ChatScreen( ChatScreen(
unreadMessageTextStyle: configuration.unreadMessageTextStyle,
service: configuration.chatService, service: configuration.chatService,
options: configuration.chatOptionsBuilder(context), options: configuration.chatOptionsBuilder(context),
onNoChats: () async => Navigator.of(context).push( onNoChats: () async => Navigator.of(context).push(
@ -84,11 +86,31 @@ Widget _chatDetailScreenRoute(
String chatId, String chatId,
) => ) =>
ChatDetailScreen( ChatDetailScreen(
chatTitleBuilder: configuration.chatTitleBuilder,
usernameBuilder: configuration.usernameBuilder,
loadingWidgetBuilder: configuration.loadingWidgetBuilder,
iconDisabledColor: configuration.iconDisabledColor,
pageSize: configuration.messagePageSize, pageSize: configuration.messagePageSize,
options: configuration.chatOptionsBuilder(context), options: configuration.chatOptionsBuilder(context),
translations: configuration.translations, translations: configuration.translations,
service: configuration.chatService, service: configuration.chatService,
chatId: chatId, chatId: chatId,
textfieldBottomPadding: configuration.textfieldBottomPadding ?? 0,
onPressUserProfile: (userId) async {
if (configuration.onPressUserProfile != null) {
return configuration.onPressUserProfile?.call();
}
return Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => _chatProfileScreenRoute(
configuration,
context,
chatId,
userId,
),
),
);
},
onMessageSubmit: (message) async { onMessageSubmit: (message) async {
if (configuration.onMessageSubmit != null) { if (configuration.onMessageSubmit != null) {
await configuration.onMessageSubmit?.call(message); await configuration.onMessageSubmit?.call(message);
@ -178,11 +200,25 @@ Widget _newChatScreenRoute(
options: configuration.chatOptionsBuilder(context), options: configuration.chatOptionsBuilder(context),
translations: configuration.translations, translations: configuration.translations,
service: configuration.chatService, service: configuration.chatService,
onPressCreateGroupChat: () async {
configuration.onPressCreateGroupChat?.call();
if (context.mounted) {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => _newGroupChatScreenRoute(
configuration,
context,
),
),
);
}
},
onPressCreateChat: (user) async { onPressCreateChat: (user) async {
configuration.onPressCreateChat?.call(user); configuration.onPressCreateChat?.call(user);
if (configuration.onPressCreateChat != null) return; if (configuration.onPressCreateChat != null) return;
var chat = await configuration.chatService.chatOverviewService var chat = await configuration.chatService.chatOverviewService
.getChatByUser(user); .getChatByUser(user);
debugPrint('Chat is ${chat.id}');
if (chat.id == null) { if (chat.id == null) {
chat = await configuration.chatService.chatOverviewService chat = await configuration.chatService.chatOverviewService
.storeChatIfNot( .storeChatIfNot(
@ -204,3 +240,64 @@ Widget _newChatScreenRoute(
} }
}, },
); );
Widget _newGroupChatScreenRoute(
ChatUserStoryConfiguration configuration,
BuildContext context,
) =>
NewGroupChatScreen(
options: configuration.chatOptionsBuilder(context),
translations: configuration.translations,
service: configuration.chatService,
onPressGroupChatOverview: (users) async => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => _newGroupChatOverviewScreenRoute(
configuration,
context,
users,
),
),
),
);
Widget _newGroupChatOverviewScreenRoute(
ChatUserStoryConfiguration configuration,
BuildContext context,
List<ChatUserModel> users,
) =>
NewGroupChatOverviewScreen(
options: configuration.chatOptionsBuilder(context),
translations: configuration.translations,
service: configuration.chatService,
users: users,
onPressCompleteGroupChatCreation: (users, groupChatName) async {
configuration.onPressCompleteGroupChatCreation
?.call(users, groupChatName);
if (configuration.onPressCreateGroupChat != null) return;
debugPrint('----------- The list of users = $users -----------');
debugPrint('----------- Group chat name = $groupChatName -----------');
var chat =
await configuration.chatService.chatOverviewService.storeChatIfNot(
GroupChatModel(
id: const Uuid().v4(),
canBeDeleted: true,
title: groupChatName,
imageUrl: 'https://picsum.photos/200/300',
users: users,
),
);
debugPrint('----------- Chat id = ${chat.id} -----------');
if (context.mounted) {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => _chatDetailScreenRoute(
configuration,
context,
chat.id!,
),
),
);
}
},
);

View file

@ -15,6 +15,7 @@ List<GoRoute> getChatStoryRoutes(
path: ChatUserStoryRoutes.chatScreen, path: ChatUserStoryRoutes.chatScreen,
pageBuilder: (context, state) { pageBuilder: (context, state) {
var chatScreen = ChatScreen( var chatScreen = ChatScreen(
unreadMessageTextStyle: configuration.unreadMessageTextStyle,
service: configuration.chatService, service: configuration.chatService,
options: configuration.chatOptionsBuilder(context), options: configuration.chatOptionsBuilder(context),
onNoChats: () async => onNoChats: () async =>
@ -53,11 +54,24 @@ List<GoRoute> getChatStoryRoutes(
pageBuilder: (context, state) { pageBuilder: (context, state) {
var chatId = state.pathParameters['id']; var chatId = state.pathParameters['id'];
var chatDetailScreen = ChatDetailScreen( var chatDetailScreen = ChatDetailScreen(
chatTitleBuilder: configuration.chatTitleBuilder,
usernameBuilder: configuration.usernameBuilder,
loadingWidgetBuilder: configuration.loadingWidgetBuilder,
iconDisabledColor: configuration.iconDisabledColor,
pageSize: configuration.messagePageSize, pageSize: configuration.messagePageSize,
options: configuration.chatOptionsBuilder(context), options: configuration.chatOptionsBuilder(context),
translations: configuration.translations, translations: configuration.translations,
service: configuration.chatService, service: configuration.chatService,
chatId: chatId!, chatId: chatId!,
textfieldBottomPadding: configuration.textfieldBottomPadding ?? 0,
onPressUserProfile: (userId) async {
if (configuration.onPressUserProfile != null) {
return configuration.onPressUserProfile?.call();
}
return context.push(
ChatUserStoryRoutes.chatProfileScreenPath(chatId, userId),
);
},
onMessageSubmit: (message) async { onMessageSubmit: (message) async {
if (configuration.onMessageSubmit != null) { if (configuration.onMessageSubmit != null) {
await configuration.onMessageSubmit?.call(message); await configuration.onMessageSubmit?.call(message);
@ -129,6 +143,33 @@ List<GoRoute> getChatStoryRoutes(
); );
} }
}, },
onPressCreateGroupChat: () async => context.push(
ChatUserStoryRoutes.newGroupChatScreen,
),
);
return buildScreenWithoutTransition(
context: context,
state: state,
child: configuration.chatPageBuilder?.call(
context,
newChatScreen,
) ??
Scaffold(
body: newChatScreen,
),
);
},
),
GoRoute(
path: ChatUserStoryRoutes.newGroupChatScreen,
pageBuilder: (context, state) {
var newChatScreen = NewGroupChatScreen(
options: configuration.chatOptionsBuilder(context),
translations: configuration.translations,
service: configuration.chatService,
onPressGroupChatOverview: (user) async => context.push(
ChatUserStoryRoutes.newGroupChatOverviewScreen,
),
); );
return buildScreenWithoutTransition( return buildScreenWithoutTransition(
context: context, context: context,

View file

@ -21,7 +21,9 @@ class ChatUserStoryConfiguration {
this.onReadChat, this.onReadChat,
this.onUploadImage, this.onUploadImage,
this.onPressCreateChat, this.onPressCreateChat,
this.iconColor, this.onPressCreateGroupChat,
this.onPressCompleteGroupChatCreation,
this.iconColor = Colors.black,
this.deleteChatDialog, this.deleteChatDialog,
this.disableDismissForPermanentChats = false, this.disableDismissForPermanentChats = false,
this.routeToNewChatIfEmpty = true, this.routeToNewChatIfEmpty = true,
@ -31,6 +33,12 @@ class ChatUserStoryConfiguration {
this.afterMessageSent, this.afterMessageSent,
this.messagePageSize = 20, this.messagePageSize = 20,
this.onPressUserProfile, this.onPressUserProfile,
this.textfieldBottomPadding = 20,
this.iconDisabledColor = Colors.grey,
this.unreadMessageTextStyle,
this.loadingWidgetBuilder,
this.usernameBuilder,
this.chatTitleBuilder,
}); });
/// The service responsible for handling chat-related functionalities. /// The service responsible for handling chat-related functionalities.
@ -65,6 +73,8 @@ class ChatUserStoryConfiguration {
final Function(ChatUserModel)? onPressCreateChat; final Function(ChatUserModel)? onPressCreateChat;
/// Builder for chat options based on context. /// Builder for chat options based on context.
final Function(List<ChatUserModel>, String)? onPressCompleteGroupChatCreation;
final Function()? onPressCreateGroupChat;
final ChatOptions Function(BuildContext context) chatOptionsBuilder; final ChatOptions Function(BuildContext context) chatOptionsBuilder;
/// If true, the user will be routed to the new chat screen if there are /// If true, the user will be routed to the new chat screen if there are
@ -91,4 +101,10 @@ class ChatUserStoryConfiguration {
/// Callback function triggered when user profile is pressed. /// Callback function triggered when user profile is pressed.
final Function()? onPressUserProfile; final Function()? onPressUserProfile;
final double? textfieldBottomPadding;
final Color? iconDisabledColor;
final TextStyle? unreadMessageTextStyle;
final Widget? Function(BuildContext context)? loadingWidgetBuilder;
final Widget Function(String userFullName)? usernameBuilder;
final Widget Function(String chatTitle)? chatTitleBuilder;
} }

View file

@ -13,6 +13,8 @@ mixin ChatUserStoryRoutes {
static const String newChatScreen = '/new-chat'; static const String newChatScreen = '/new-chat';
/// Constructs the path for the chat profile screen. /// Constructs the path for the chat profile screen.
static const String newGroupChatScreen = '/new-group-chat';
static const String newGroupChatOverviewScreen = '/new-group-chat-overview';
static String chatProfileScreenPath(String chatId, String? userId) => static String chatProfileScreenPath(String chatId, String? userId) =>
'/chat-profile/$chatId/$userId'; '/chat-profile/$chatId/$userId';

View file

@ -4,7 +4,7 @@
name: flutter_chat name: flutter_chat
description: A new Flutter package project. description: A new Flutter package project.
version: 1.2.1 version: 1.4.0
publish_to: none publish_to: none
@ -20,17 +20,18 @@ dependencies:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_view path: packages/flutter_chat_view
ref: 1.2.1 ref: 1.4.0
flutter_chat_interface: flutter_chat_interface:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_interface path: packages/flutter_chat_interface
ref: 1.2.1 ref: 1.4.0
flutter_chat_local: flutter_chat_local:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_local path: packages/flutter_chat_local
ref: 1.2.1 ref: 1.4.0
uuid: ^4.3.3
dev_dependencies: dev_dependencies:
flutter_iconica_analysis: flutter_iconica_analysis:

View file

@ -238,6 +238,9 @@ class FirebaseChatDetailService
onCancel: () async { onCancel: () async {
await _subscription?.cancel(); await _subscription?.cancel();
_subscription = null; _subscription = null;
_cumulativeMessages = [];
lastChat = chatId;
lastMessage = null;
debugPrint('Canceling messages stream'); debugPrint('Canceling messages stream');
}, },
); );
@ -259,14 +262,16 @@ class FirebaseChatDetailService
/// [pageSize]: The number of messages to fetch. /// [pageSize]: The number of messages to fetch.
/// [chatId]: The ID of the chat. /// [chatId]: The ID of the chat.
@override @override
Future<void> fetchMoreMessage(int pageSize, String chatId) async { Future<void> fetchMoreMessage(
if (lastChat == null) { int pageSize,
lastChat = chatId; String chatId,
} else if (lastChat != chatId) { ) async {
if (lastChat != chatId) {
_cumulativeMessages = []; _cumulativeMessages = [];
lastChat = chatId; lastChat = chatId;
lastMessage = null; lastMessage = null;
} }
// get the x amount of last messages from the oldest message that is in // get the x amount of last messages from the oldest message that is in
// cumulative messages and add that to the list // cumulative messages and add that to the list
var messages = <ChatMessageModel>[]; var messages = <ChatMessageModel>[];

View file

@ -90,11 +90,13 @@ class FirebaseChatOverviewService implements ChatOverviewService {
for (var element in event.docChanges) { for (var element in event.docChanges) {
var chat = element.doc.data(); var chat = element.doc.data();
if (chat == null) return; if (chat == null) return;
var otherUser = await _userService.getUser( var otherUser = await _userService.getUser(
chat.users.firstWhere( chat.users.firstWhere(
(element) => element != currentUser?.id, (element) => element != currentUser?.id,
), ),
); );
var unread = var unread =
await _addUnreadChatSubscription(chat.id!, currentUser!.id!); await _addUnreadChatSubscription(chat.id!, currentUser!.id!);

View file

@ -4,7 +4,7 @@
name: flutter_chat_firebase name: flutter_chat_firebase
description: A new Flutter package project. description: A new Flutter package project.
version: 1.2.1 version: 1.4.0
publish_to: none publish_to: none
environment: environment:
@ -23,7 +23,7 @@ dependencies:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_interface path: packages/flutter_chat_interface
ref: 1.2.1 ref: 1.4.0
dev_dependencies: dev_dependencies:
flutter_iconica_analysis: flutter_iconica_analysis:

View file

@ -6,6 +6,7 @@
import 'package:flutter_chat_interface/flutter_chat_interface.dart'; import 'package:flutter_chat_interface/flutter_chat_interface.dart';
abstract class ChatModelInterface { abstract class ChatModelInterface {
ChatModelInterface copyWith();
String? get id; String? get id;
List<ChatMessageModel>? get messages; List<ChatMessageModel>? get messages;
int? get unreadMessages; int? get unreadMessages;
@ -55,4 +56,22 @@ class ChatModel implements ChatModelInterface {
@override @override
final bool canBeDeleted; final bool canBeDeleted;
@override
ChatModel copyWith({
String? id,
List<ChatMessageModel>? messages,
int? unreadMessages,
DateTime? lastUsed,
ChatMessageModel? lastMessage,
bool? canBeDeleted,
}) =>
ChatModel(
id: id ?? this.id,
messages: messages ?? this.messages,
unreadMessages: unreadMessages ?? this.unreadMessages,
lastUsed: lastUsed ?? this.lastUsed,
lastMessage: lastMessage ?? this.lastMessage,
canBeDeleted: canBeDeleted ?? this.canBeDeleted,
);
} }

View file

@ -19,6 +19,7 @@ abstract class GroupChatModelInterface extends ChatModel {
String get imageUrl; String get imageUrl;
List<ChatUserModel> get users; List<ChatUserModel> get users;
@override
GroupChatModelInterface copyWith({ GroupChatModelInterface copyWith({
String? id, String? id,
List<ChatMessageModel>? messages, List<ChatMessageModel>? messages,

View file

@ -17,6 +17,7 @@ abstract class PersonalChatModelInterface extends ChatModel {
ChatUserModel get user; ChatUserModel get user;
@override
PersonalChatModel copyWith({ PersonalChatModel copyWith({
String? id, String? id,
List<ChatMessageModel>? messages, List<ChatMessageModel>? messages,

View file

@ -21,8 +21,10 @@ abstract class ChatDetailService with ChangeNotifier {
String chatId, String chatId,
); );
/// Fetches more messages for the specified chat with a given page size. Future<void> fetchMoreMessage(
Future<void> fetchMoreMessage(int pageSize, String chatId); int pageSize,
String chatId,
);
/// Retrieves the list of messages for the chat. /// Retrieves the list of messages for the chat.
List<ChatMessageModel> getMessages(); List<ChatMessageModel> getMessages();

View file

@ -4,7 +4,7 @@
name: flutter_chat_interface name: flutter_chat_interface
description: A new Flutter package project. description: A new Flutter package project.
version: 1.2.1 version: 1.4.0
publish_to: none publish_to: none
environment: environment:

View file

@ -25,7 +25,10 @@ class LocalChatDetailService with ChangeNotifier implements ChatDetailService {
late StreamSubscription? _subscription; late StreamSubscription? _subscription;
@override @override
Future<void> fetchMoreMessage(int pageSize, String chatId) async { Future<void> fetchMoreMessage(
int pageSize,
String chatId,
) async {
await chatOverviewService.getChatById(chatId).then((value) { await chatOverviewService.getChatById(chatId).then((value) {
_cumulativeMessages.clear(); _cumulativeMessages.clear();
_cumulativeMessages.addAll(value.messages!); _cumulativeMessages.addAll(value.messages!);
@ -39,7 +42,9 @@ class LocalChatDetailService with ChangeNotifier implements ChatDetailService {
List<ChatMessageModel> getMessages() => _cumulativeMessages; List<ChatMessageModel> getMessages() => _cumulativeMessages;
@override @override
Stream<List<ChatMessageModel>> getMessagesStream(String chatId) { Stream<List<ChatMessageModel>> getMessagesStream(
String chatId,
) {
_controller.onListen = () async { _controller.onListen = () async {
_subscription = _subscription =
chatOverviewService.getChatById(chatId).asStream().listen((event) { chatOverviewService.getChatById(chatId).asStream().listen((event) {
@ -73,7 +78,7 @@ class LocalChatDetailService with ChangeNotifier implements ChatDetailService {
await (chatOverviewService as LocalChatOverviewService).updateChat( await (chatOverviewService as LocalChatOverviewService).updateChat(
chat.copyWith( chat.copyWith(
messages: [...chat.messages!, message], messages: [...?chat.messages, message],
lastMessage: message, lastMessage: message,
lastUsed: DateTime.now(), lastUsed: DateTime.now(),
), ),
@ -105,7 +110,7 @@ class LocalChatDetailService with ChangeNotifier implements ChatDetailService {
); );
await (chatOverviewService as LocalChatOverviewService).updateChat( await (chatOverviewService as LocalChatOverviewService).updateChat(
chat.copyWith( chat.copyWith(
messages: [...chat.messages!, message], messages: [...?chat.messages, message],
lastMessage: message, lastMessage: message,
lastUsed: DateTime.now(), lastUsed: DateTime.now(),
), ),

View file

@ -8,10 +8,10 @@ class LocalChatOverviewService
with ChangeNotifier with ChangeNotifier
implements ChatOverviewService { implements ChatOverviewService {
/// The list of personal chat models. /// The list of personal chat models.
final List<PersonalChatModel> _chats = []; final List<ChatModel> _chats = [];
/// Retrieves the list of personal chat models. /// Retrieves the list of personal chat models.
List<PersonalChatModel> get chats => _chats; List<ChatModel> get chats => _chats;
/// The stream controller for chats. /// The stream controller for chats.
final StreamController<List<ChatModel>> _chatsController = final StreamController<List<ChatModel>> _chatsController =
@ -19,9 +19,10 @@ class LocalChatOverviewService
Future<void> updateChat(ChatModel chat) { Future<void> updateChat(ChatModel chat) {
var index = _chats.indexWhere((element) => element.id == chat.id); var index = _chats.indexWhere((element) => element.id == chat.id);
_chats[index] = chat as PersonalChatModel; _chats[index] = chat;
_chatsController.addStream(Stream.value(_chats)); _chatsController.addStream(Stream.value(_chats));
notifyListeners(); notifyListeners();
debugPrint('Chat updated: $chat');
return Future.value(); return Future.value();
} }
@ -30,24 +31,27 @@ class LocalChatOverviewService
_chats.removeWhere((element) => element.id == chat.id); _chats.removeWhere((element) => element.id == chat.id);
_chatsController.add(_chats); _chatsController.add(_chats);
notifyListeners(); notifyListeners();
debugPrint('Chat deleted: $chat');
return Future.value(); return Future.value();
} }
@override @override
Future<ChatModel> getChatById(String id) => Future<ChatModel> getChatById(String id) {
Future.value(_chats.firstWhere((element) => element.id == id)); var chat = _chats.firstWhere((element) => element.id == id);
debugPrint('Retrieved chat by ID: $chat');
debugPrint('Messages are: ${chat.messages?.length}');
return Future.value(chat);
}
@override @override
Future<ChatModel> getChatByUser(ChatUserModel user) { Future<PersonalChatModel> getChatByUser(ChatUserModel user) async {
PersonalChatModel? chat; PersonalChatModel? chat;
try { try {
chat = _chats.firstWhere( chat = _chats
(element) => element.user.id == user.id, .whereType<PersonalChatModel>()
orElse: () { .firstWhere((element) => element.user.id == user.id);
throw Exception(); // ignore: avoid_catching_errors
}, } on StateError {
);
} on Exception catch (_) {
chat = PersonalChatModel( chat = PersonalChatModel(
user: user, user: user,
messages: [], messages: [],
@ -55,11 +59,12 @@ class LocalChatOverviewService
); );
chat.id = chat.hashCode.toString(); chat.id = chat.hashCode.toString();
_chats.add(chat); _chats.add(chat);
debugPrint('New chat created: $chat');
} }
_chatsController.add([..._chats]); _chatsController.add([..._chats]);
notifyListeners(); notifyListeners();
return Future.value(chat); return chat;
} }
@override @override
@ -72,5 +77,18 @@ class LocalChatOverviewService
Future<void> readChat(ChatModel chat) async => Future.value(); Future<void> readChat(ChatModel chat) async => Future.value();
@override @override
Future<ChatModel> storeChatIfNot(ChatModel chat) => Future.value(chat); Future<ChatModel> storeChatIfNot(ChatModel chat) {
var chatExists = _chats.any((element) => element.id == chat.id);
if (!chatExists) {
_chats.add(chat);
_chatsController.add([..._chats]);
notifyListeners();
debugPrint('Chat stored: $chat');
} else {
debugPrint('Chat already exists: $chat');
}
return Future.value(chat);
}
} }

View file

@ -16,10 +16,17 @@ class LocalChatUserService implements ChatUserService {
lastName: 'Doe', lastName: 'Doe',
imageUrl: 'https://picsum.photos/200/300', imageUrl: 'https://picsum.photos/200/300',
), ),
ChatUserModel(
id: '3',
firstName: 'ico',
lastName: 'nica',
imageUrl: 'https://picsum.photos/100/200',
),
]; ];
@override @override
Future<List<ChatUserModel>> getAllUsers() => Future.value(users); Future<List<ChatUserModel>> getAllUsers() =>
Future.value(users.where((element) => element.id != '3').toList());
@override @override
Future<ChatUserModel?> getCurrentUser() => Future.value(ChatUserModel()); Future<ChatUserModel?> getCurrentUser() => Future.value(ChatUserModel());

View file

@ -1,6 +1,6 @@
name: flutter_chat_local name: flutter_chat_local
description: "A new Flutter package project." description: "A new Flutter package project."
version: 1.2.1 version: 1.4.0
publish_to: none publish_to: none
homepage: homepage:
@ -15,7 +15,7 @@ dependencies:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_interface path: packages/flutter_chat_interface
ref: 1.2.1 ref: 1.4.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

View file

@ -13,3 +13,5 @@ export 'src/screens/chat_detail_screen.dart';
export 'src/screens/chat_profile_screen.dart'; export 'src/screens/chat_profile_screen.dart';
export 'src/screens/chat_screen.dart'; export 'src/screens/chat_screen.dart';
export 'src/screens/new_chat_screen.dart'; export 'src/screens/new_chat_screen.dart';
export 'src/screens/new_group_chat_overview_screen.dart';
export 'src/screens/new_group_chat_screen.dart';

View file

@ -13,6 +13,7 @@ class ChatBottom extends StatefulWidget {
required this.translations, required this.translations,
this.onPressSelectImage, this.onPressSelectImage,
this.iconColor, this.iconColor,
this.iconDisabledColor,
super.key, super.key,
}); });
@ -33,6 +34,7 @@ class ChatBottom extends StatefulWidget {
/// The color of the icons. /// The color of the icons.
final Color? iconColor; final Color? iconColor;
final Color? iconDisabledColor;
@override @override
State<ChatBottom> createState() => _ChatBottomState(); State<ChatBottom> createState() => _ChatBottomState();
@ -40,20 +42,30 @@ class ChatBottom extends StatefulWidget {
class _ChatBottomState extends State<ChatBottom> { class _ChatBottomState extends State<ChatBottom> {
final TextEditingController _textEditingController = TextEditingController(); final TextEditingController _textEditingController = TextEditingController();
bool _isTyping = false;
@override @override
Widget build(BuildContext context) => Padding( Widget build(BuildContext context) {
_textEditingController.addListener(() {
if (_textEditingController.text.isEmpty) {
setState(() {
_isTyping = false;
});
} else {
setState(() {
_isTyping = true;
});
}
});
return Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 14, horizontal: 12,
vertical: 17, vertical: 16,
), ),
child: SizedBox( child: SizedBox(
height: 45, height: 45,
child: widget.messageInputBuilder( child: widget.messageInputBuilder(
_textEditingController, _textEditingController,
Padding( Row(
padding: const EdgeInsets.only(right: 15.0),
child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
IconButton( IconButton(
@ -64,24 +76,27 @@ class _ChatBottomState extends State<ChatBottom> {
), ),
), ),
IconButton( IconButton(
onPressed: () async { disabledColor: widget.iconDisabledColor,
color: widget.iconColor,
onPressed: _isTyping
? () async {
var value = _textEditingController.text; var value = _textEditingController.text;
if (value.isNotEmpty) { if (value.isNotEmpty) {
await widget.onMessageSubmit(value); await widget.onMessageSubmit(value);
_textEditingController.clear(); _textEditingController.clear();
} }
}, }
icon: Icon( : null,
icon: const Icon(
Icons.send, Icons.send,
color: widget.iconColor,
), ),
), ),
], ],
), ),
),
widget.translations, widget.translations,
), ),
), ),
); );
} }
}

View file

@ -13,6 +13,8 @@ class ChatDetailRow extends StatefulWidget {
required this.translations, required this.translations,
required this.message, required this.message,
required this.userAvatarBuilder, required this.userAvatarBuilder,
required this.onPressUserProfile,
this.usernameBuilder,
this.previousMessage, this.previousMessage,
this.showTime = false, this.showTime = false,
super.key, super.key,
@ -29,6 +31,8 @@ class ChatDetailRow extends StatefulWidget {
/// The previous chat message model. /// The previous chat message model.
final ChatMessageModel? previousMessage; final ChatMessageModel? previousMessage;
final Function(String? userId) onPressUserProfile;
final Widget Function(String userFullName)? usernameBuilder;
/// Flag indicating whether to show the time. /// Flag indicating whether to show the time.
final bool showTime; final bool showTime;
@ -46,6 +50,10 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
widget.message.timestamp.day != widget.previousMessage?.timestamp.day; widget.message.timestamp.day != widget.previousMessage?.timestamp.day;
var isSameSender = widget.previousMessage == null || var isSameSender = widget.previousMessage == null ||
widget.previousMessage?.sender.id != widget.message.sender.id; widget.previousMessage?.sender.id != widget.message.sender.id;
var isSameMinute = widget.previousMessage != null &&
widget.message.timestamp.minute ==
widget.previousMessage?.timestamp.minute;
var hasHeader = isNewDate || isSameSender;
return Padding( return Padding(
padding: EdgeInsets.only( padding: EdgeInsets.only(
@ -55,7 +63,11 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (isNewDate || isSameSender) ...[ if (isNewDate || isSameSender) ...[
Padding( GestureDetector(
onTap: () => widget.onPressUserProfile(
widget.message.sender.id,
),
child: Padding(
padding: const EdgeInsets.only(left: 10.0), padding: const EdgeInsets.only(left: 10.0),
child: widget.message.sender.imageUrl != null && child: widget.message.sender.imageUrl != null &&
widget.message.sender.imageUrl!.isNotEmpty widget.message.sender.imageUrl!.isNotEmpty
@ -64,7 +76,8 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
) )
: widget.userAvatarBuilder( : widget.userAvatarBuilder(
widget.message.sender, widget.message.sender,
30, 40,
),
), ),
), ),
] else ...[ ] else ...[
@ -83,14 +96,21 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
if (widget.usernameBuilder != null)
widget.usernameBuilder!(
widget.message.sender.fullName ?? '',
)
else
Text( Text(
widget.message.sender.fullName?.toUpperCase() ?? widget.message.sender.fullName?.toUpperCase() ??
widget.translations.anonymousUser, widget.translations.anonymousUser,
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
color: color: Theme.of(context)
Theme.of(context).textTheme.labelMedium?.color, .textTheme
.labelMedium
?.color,
), ),
), ),
Padding( Padding(
@ -111,9 +131,12 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
Padding( Padding(
padding: const EdgeInsets.only(top: 3.0), padding: const EdgeInsets.only(top: 3.0),
child: widget.message is ChatTextMessageModel child: widget.message is ChatTextMessageModel
? RichText( ? Row(
text: TextSpan( crossAxisAlignment: CrossAxisAlignment.end,
text: mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
(widget.message as ChatTextMessageModel).text, (widget.message as ChatTextMessageModel).text,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
@ -122,24 +145,27 @@ class _ChatDetailRowState extends State<ChatDetailRow> {
.labelMedium .labelMedium
?.color, ?.color,
), ),
children: <TextSpan>[ ),
if (widget.showTime) ),
TextSpan( if (widget.showTime &&
text: " ${_dateFormatter.format( !isSameMinute &&
!isNewDate &&
!hasHeader)
Text(
_dateFormatter
.format(
date: widget.message.timestamp, date: widget.message.timestamp,
showFullDate: true, showFullDate: true,
).split(' ').last}", )
.split(' ')
.last,
style: const TextStyle( style: const TextStyle(
fontSize: 12, fontSize: 12,
color: Color(0xFFBBBBBB), color: Color(0xFFBBBBBB),
), ),
) textAlign: TextAlign.end,
else
const TextSpan(),
],
), ),
overflow: TextOverflow.ellipsis, ],
maxLines: 999,
) )
: CachedNetworkImage( : CachedNetworkImage(
imageUrl: (widget.message as ChatImageMessageModel) imageUrl: (widget.message as ChatImageMessageModel)

View file

@ -35,6 +35,7 @@ class ChatImage extends StatelessWidget {
height: size, height: size,
child: image.isNotEmpty child: image.isNotEmpty
? CachedNetworkImage( ? CachedNetworkImage(
fadeInDuration: Duration.zero,
imageUrl: image, imageUrl: image,
fit: BoxFit.cover, fit: BoxFit.cover,
) )

View file

@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_chat_view/flutter_chat_view.dart'; import 'package:flutter_chat_view/flutter_chat_view.dart';
import 'package:flutter_chat_view/src/components/chat_image.dart'; import 'package:flutter_chat_view/src/components/chat_image.dart';
import 'package:flutter_image_picker/flutter_image_picker.dart'; import 'package:flutter_image_picker/flutter_image_picker.dart';
import 'package:flutter_profile/flutter_profile.dart';
class ChatOptions { class ChatOptions {
const ChatOptions({ const ChatOptions({
@ -50,13 +51,17 @@ Widget _createNewChatButton(
ChatTranslations translations, ChatTranslations translations,
) => ) =>
Padding( Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(24.0),
child: ElevatedButton( child: ElevatedButton(
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.black,
minimumSize: const Size.fromHeight(50), minimumSize: const Size.fromHeight(50),
), ),
onPressed: onPressed, onPressed: onPressed,
child: Text(translations.newChatButton), child: Text(
translations.newChatButton,
style: const TextStyle(color: Colors.white),
),
), ),
); );
@ -66,9 +71,38 @@ Widget _createMessageInput(
ChatTranslations translations, ChatTranslations translations,
) => ) =>
TextField( TextField(
textCapitalization: TextCapitalization.sentences,
controller: textEditingController, controller: textEditingController,
decoration: InputDecoration( decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(26.5),
borderSide: const BorderSide(
color: Colors.black,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(26.5),
borderSide: const BorderSide(
color: Colors.black,
),
),
contentPadding: const EdgeInsets.symmetric(
vertical: 0,
horizontal: 30,
),
hintText: translations.messagePlaceholder, hintText: translations.messagePlaceholder,
hintStyle: const TextStyle(
fontWeight: FontWeight.normal,
color: Colors.black,
),
fillColor: Colors.white,
filled: true,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(26.5),
),
borderSide: BorderSide.none,
),
suffixIcon: suffixIcon, suffixIcon: suffixIcon,
), ),
); );
@ -93,9 +127,13 @@ Widget _createImagePickerContainer(
color: Colors.white, color: Colors.white,
child: ImagePicker( child: ImagePicker(
customButton: ElevatedButton( customButton: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black,
),
onPressed: onClose, onPressed: onClose,
child: Text( child: Text(
translations.cancelImagePickerBtn, translations.cancelImagePickerBtn,
style: const TextStyle(color: Colors.white),
), ),
), ),
), ),
@ -114,8 +152,12 @@ Widget _createUserAvatar(
ChatUserModel user, ChatUserModel user,
double size, double size,
) => ) =>
ChatImage( Avatar(
image: user.imageUrl ?? '', user: User(
firstName: user.firstName,
lastName: user.lastName,
imageUrl: user.imageUrl,
),
size: size, size: size,
); );
Widget _createGroupAvatar( Widget _createGroupAvatar(

View file

@ -7,6 +7,7 @@ class ChatTranslations {
this.chatsTitle = 'Chats', this.chatsTitle = 'Chats',
this.chatsUnread = 'unread', this.chatsUnread = 'unread',
this.newChatButton = 'Start chat', this.newChatButton = 'Start chat',
this.newGroupChatButton = 'Start group chat',
this.newChatTitle = 'Start chat', this.newChatTitle = 'Start chat',
this.image = 'Image', this.image = 'Image',
this.searchPlaceholder = 'Search...', this.searchPlaceholder = 'Search...',
@ -28,6 +29,7 @@ class ChatTranslations {
final String chatsTitle; final String chatsTitle;
final String chatsUnread; final String chatsUnread;
final String newChatButton; final String newChatButton;
final String newGroupChatButton;
final String newChatTitle; final String newChatTitle;
final String deleteChatButton; final String deleteChatButton;
final String image; final String image;

View file

@ -6,7 +6,6 @@ import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_chat_view/flutter_chat_view.dart'; import 'package:flutter_chat_view/flutter_chat_view.dart';
import 'package:flutter_chat_view/src/components/chat_bottom.dart'; import 'package:flutter_chat_view/src/components/chat_bottom.dart';
import 'package:flutter_chat_view/src/components/chat_detail_row.dart'; import 'package:flutter_chat_view/src/components/chat_detail_row.dart';
@ -21,9 +20,15 @@ class ChatDetailScreen extends StatefulWidget {
required this.service, required this.service,
required this.pageSize, required this.pageSize,
required this.chatId, required this.chatId,
required this.textfieldBottomPadding,
required this.onPressChatTitle,
required this.onPressUserProfile,
this.chatTitleBuilder,
this.usernameBuilder,
this.loadingWidgetBuilder,
this.translations = const ChatTranslations(), this.translations = const ChatTranslations(),
this.onPressChatTitle,
this.iconColor, this.iconColor,
this.iconDisabledColor,
this.showTime = false, this.showTime = false,
super.key, super.key,
}); });
@ -39,13 +44,20 @@ class ChatDetailScreen extends StatefulWidget {
// called at the start of the screen to set the chat to read // called at the start of the screen to set the chat to read
// or when a new message is received // or when a new message is received
final Future<void> Function(ChatModel chat) onReadChat; final Future<void> Function(ChatModel chat) onReadChat;
final Function(BuildContext context, ChatModel chat)? onPressChatTitle; final Function(BuildContext context, ChatModel chat) onPressChatTitle;
/// The color of the icon buttons in the chat bottom. /// The color of the icon buttons in the chat bottom.
final Color? iconColor; final Color? iconColor;
final bool showTime; final bool showTime;
final ChatService service; final ChatService service;
final int pageSize; final int pageSize;
final double textfieldBottomPadding;
final Color? iconDisabledColor;
final Function(String? userId) onPressUserProfile;
// ignore: avoid_positional_boolean_parameters
final Widget? Function(BuildContext context)? loadingWidgetBuilder;
final Widget Function(String userFullName)? usernameBuilder;
final Widget Function(String chatTitle)? chatTitleBuilder;
@override @override
State<ChatDetailScreen> createState() => _ChatDetailScreenState(); State<ChatDetailScreen> createState() => _ChatDetailScreenState();
@ -71,7 +83,7 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
chat = chat =
await widget.service.chatOverviewService.getChatById(widget.chatId); await widget.service.chatOverviewService.getChatById(widget.chatId);
if (detailRows.isEmpty) { if (detailRows.isEmpty && context.mounted) {
await widget.service.chatDetailService.fetchMoreMessage( await widget.service.chatDetailService.fetchMoreMessage(
widget.pageSize, widget.pageSize,
chat!.id!, chat!.id!,
@ -99,6 +111,8 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
translations: widget.translations, translations: widget.translations,
userAvatarBuilder: widget.options.userAvatarBuilder, userAvatarBuilder: widget.options.userAvatarBuilder,
previousMessage: previousMessage, previousMessage: previousMessage,
onPressUserProfile: widget.onPressUserProfile,
usernameBuilder: widget.usernameBuilder,
), ),
); );
previousMessage = message; previousMessage = message;
@ -123,6 +137,8 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
var theme = Theme.of(context);
Future<void> onPressSelectImage() async => showModalBottomSheet<Uint8List?>( Future<void> onPressSelectImage() async => showModalBottomSheet<Uint8List?>(
context: context, context: context,
builder: (BuildContext context) => builder: (BuildContext context) =>
@ -132,14 +148,13 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
), ),
).then( ).then(
(image) async { (image) async {
if (image == null) return;
var messenger = ScaffoldMessenger.of(context) var messenger = ScaffoldMessenger.of(context)
..showSnackBar( ..showSnackBar(
getImageLoadingSnackbar(widget.translations), getImageLoadingSnackbar(widget.translations),
) )
..activate(); ..activate();
if (image != null) {
await widget.onUploadImage(image); await widget.onUploadImage(image);
}
Future.delayed(const Duration(seconds: 1), () { Future.delayed(const Duration(seconds: 1), () {
messenger.hideCurrentSnackBar(); messenger.hideCurrentSnackBar();
}); });
@ -153,9 +168,22 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
var chatModel = snapshot.data; var chatModel = snapshot.data;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
iconTheme: theme.appBarTheme.iconTheme ??
const IconThemeData(color: Colors.white),
centerTitle: true, centerTitle: true,
leading: (chatModel is GroupChatModel)
? GestureDetector(
onTap: () {
Navigator.popUntil(context, (route) => route.isFirst);
},
child: const Icon(
Icons.arrow_back,
),
)
: null,
title: GestureDetector( title: GestureDetector(
onTap: () => widget.onPressChatTitle?.call(context, chatModel!), onTap: () => widget.onPressChatTitle.call(context, chatModel!),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: chat == null children: chat == null
@ -177,14 +205,28 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
Expanded( Expanded(
child: Padding( child: Padding(
padding: const EdgeInsets.only(left: 15.5), padding: const EdgeInsets.only(left: 15.5),
child: Text( child: widget.chatTitleBuilder != null
? widget.chatTitleBuilder!.call(
(chatModel is GroupChatModel) (chatModel is GroupChatModel)
? chatModel.title ? chatModel.title
: (chatModel is PersonalChatModel) : (chatModel is PersonalChatModel)
? chatModel.user.fullName ?? ? chatModel.user.fullName ??
widget.translations.anonymousUser widget
.translations.anonymousUser
: '', : '',
style: const TextStyle(fontSize: 18), )
: Text(
(chatModel is GroupChatModel)
? chatModel.title
: (chatModel is PersonalChatModel)
? chatModel.user.fullName ??
widget
.translations.anonymousUser
: '',
style: theme.appBarTheme.titleTextStyle ??
const TextStyle(
color: Colors.white,
),
), ),
), ),
), ),
@ -192,23 +234,25 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
), ),
), ),
), ),
body: Column( body: Stack(
children: [
Column(
children: [ children: [
Expanded( Expanded(
child: Listener( child: Listener(
onPointerMove: (event) async { onPointerMove: (event) async {
var isTop = controller.position.pixels ==
controller.position.maxScrollExtent;
if (!showIndicator && if (!showIndicator &&
!isTop && controller.offset >=
controller.position.userScrollDirection == controller.position.maxScrollExtent &&
ScrollDirection.reverse) { !controller.position.outOfRange) {
setState(() { setState(() {
showIndicator = true; showIndicator = true;
}); });
await widget.service.chatDetailService await widget.service.chatDetailService
.fetchMoreMessage(widget.pageSize, widget.chatId); .fetchMoreMessage(
widget.pageSize,
widget.chatId,
);
Future.delayed(const Duration(seconds: 2), () { Future.delayed(const Duration(seconds: 2), () {
if (mounted) { if (mounted) {
setState(() { setState(() {
@ -226,15 +270,6 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
padding: const EdgeInsets.only(top: 24.0), padding: const EdgeInsets.only(top: 24.0),
children: [ children: [
...detailRows, ...detailRows,
if (showIndicator) ...[
const SizedBox(
height: 10,
),
const Center(child: CircularProgressIndicator()),
const SizedBox(
height: 10,
),
],
], ],
), ),
), ),
@ -247,6 +282,25 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
onMessageSubmit: widget.onMessageSubmit, onMessageSubmit: widget.onMessageSubmit,
translations: widget.translations, translations: widget.translations,
iconColor: widget.iconColor, iconColor: widget.iconColor,
iconDisabledColor: widget.iconDisabledColor,
),
SizedBox(
height: widget.textfieldBottomPadding,
),
],
),
if (showIndicator)
widget.loadingWidgetBuilder?.call(context) ??
const Column(
children: [
SizedBox(
height: 10,
),
Center(child: CircularProgressIndicator()),
SizedBox(
height: 10,
),
],
), ),
], ],
), ),

View file

@ -37,6 +37,7 @@ class _ProfileScreenState extends State<ChatProfileScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
var size = MediaQuery.of(context).size; var size = MediaQuery.of(context).size;
var hasUser = widget.userId == null; var hasUser = widget.userId == null;
var theme = Theme.of(context);
return FutureBuilder<dynamic>( return FutureBuilder<dynamic>(
future: hasUser future: hasUser
// ignore: discarded_futures // ignore: discarded_futures
@ -69,6 +70,9 @@ class _ProfileScreenState extends State<ChatProfileScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
iconTheme: theme.appBarTheme.iconTheme ??
const IconThemeData(color: Colors.white),
title: Text( title: Text(
(data is ChatUserModel) (data is ChatUserModel)
? '${data.firstName ?? ''} ${data.lastName ?? ''}' ? '${data.firstName ?? ''} ${data.lastName ?? ''}'
@ -77,6 +81,10 @@ class _ProfileScreenState extends State<ChatProfileScreen> {
: (data is GroupChatModel) : (data is GroupChatModel)
? data.title ? data.title
: '', : '',
style: theme.appBarTheme.titleTextStyle ??
const TextStyle(
color: Colors.white,
),
), ),
), ),
body: snapshot.hasData body: snapshot.hasData

View file

@ -17,6 +17,7 @@ class ChatScreen extends StatefulWidget {
required this.onPressChat, required this.onPressChat,
required this.onDeleteChat, required this.onDeleteChat,
required this.service, required this.service,
this.unreadMessageTextStyle,
this.onNoChats, this.onNoChats,
this.deleteChatDialog, this.deleteChatDialog,
this.translations = const ChatTranslations(), this.translations = const ChatTranslations(),
@ -50,6 +51,7 @@ class ChatScreen extends StatefulWidget {
/// Disables the swipe to dismiss feature for chats that are not deletable. /// Disables the swipe to dismiss feature for chats that are not deletable.
final bool disableDismissForPermanentChats; final bool disableDismissForPermanentChats;
final TextStyle? unreadMessageTextStyle;
@override @override
State<ChatScreen> createState() => _ChatScreenState(); State<ChatScreen> createState() => _ChatScreenState();
@ -72,9 +74,17 @@ class _ChatScreenState extends State<ChatScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
var translations = widget.translations; var translations = widget.translations;
var theme = Theme.of(context);
return widget.options.scaffoldBuilder( return widget.options.scaffoldBuilder(
AppBar( AppBar(
title: Text(translations.chatsTitle), backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
title: Text(
translations.chatsTitle,
style: theme.appBarTheme.titleTextStyle ??
const TextStyle(
color: Colors.white,
),
),
centerTitle: true, centerTitle: true,
actions: [ actions: [
StreamBuilder<int>( StreamBuilder<int>(
@ -86,8 +96,9 @@ class _ChatScreenState extends State<ChatScreen> {
padding: const EdgeInsets.only(right: 22.0), padding: const EdgeInsets.only(right: 22.0),
child: Text( child: Text(
'${snapshot.data ?? 0} ${translations.chatsUnread}', '${snapshot.data ?? 0} ${translations.chatsUnread}',
style: const TextStyle( style: widget.unreadMessageTextStyle ??
color: Color(0xFFBBBBBB), const TextStyle(
color: Colors.white,
fontSize: 14, fontSize: 14,
), ),
), ),

View file

@ -10,6 +10,7 @@ class NewChatScreen extends StatefulWidget {
required this.options, required this.options,
required this.onPressCreateChat, required this.onPressCreateChat,
required this.service, required this.service,
required this.onPressCreateGroupChat,
this.translations = const ChatTranslations(), this.translations = const ChatTranslations(),
super.key, super.key,
}); });
@ -22,6 +23,7 @@ class NewChatScreen extends StatefulWidget {
/// Callback function for creating a new chat with a user. /// Callback function for creating a new chat with a user.
final Function(ChatUserModel) onPressCreateChat; final Function(ChatUserModel) onPressCreateChat;
final Function() onPressCreateGroupChat;
/// Translations for the chat. /// Translations for the chat.
final ChatTranslations translations; final ChatTranslations translations;
@ -36,14 +38,64 @@ class _NewChatScreenState extends State<NewChatScreen> {
String query = ''; String query = '';
@override @override
Widget build(BuildContext context) => Scaffold( Widget build(BuildContext context) {
var theme = Theme.of(context);
return Scaffold(
appBar: AppBar( appBar: AppBar(
iconTheme: theme.appBarTheme.iconTheme ??
const IconThemeData(color: Colors.white),
backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
title: _buildSearchField(), title: _buildSearchField(),
actions: [ actions: [
_buildSearchIcon(), _buildSearchIcon(),
], ],
), ),
body: FutureBuilder<List<ChatUserModel>>( body: Column(
children: [
GestureDetector(
onTap: () async {
await widget.onPressCreateGroupChat();
},
child: Container(
color: Colors.grey[900],
child: SizedBox(
height: 60.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
left: 16.0,
),
child: IconButton(
icon: const Icon(
Icons.group,
color: Colors.white,
),
onPressed: () {
// Handle group chat creation
},
),
),
const Text(
'Create group chat',
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
),
),
],
),
],
),
),
),
),
Expanded(
child: FutureBuilder<List<ChatUserModel>>(
// ignore: discarded_futures // ignore: discarded_futures
future: widget.service.chatUserService.getAllUsers(), future: widget.service.chatUserService.getAllUsers(),
builder: (context, snapshot) { builder: (context, snapshot) {
@ -59,9 +111,16 @@ class _NewChatScreenState extends State<NewChatScreen> {
} }
}, },
), ),
),
],
),
); );
}
Widget _buildSearchField() => _isSearching Widget _buildSearchField() {
var theme = Theme.of(context);
return _isSearching
? Padding( ? Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0), padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextField( child: TextField(
@ -73,15 +132,42 @@ class _NewChatScreenState extends State<NewChatScreen> {
}, },
decoration: InputDecoration( decoration: InputDecoration(
hintText: widget.translations.searchPlaceholder, hintText: widget.translations.searchPlaceholder,
hintStyle: theme.inputDecorationTheme.hintStyle ??
const TextStyle(
color: Colors.white,
), ),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: theme.inputDecorationTheme.focusedBorder?.borderSide
.color ??
Colors.white,
),
),
),
style: theme.inputDecorationTheme.hintStyle ??
const TextStyle(
color: Colors.white,
),
cursorColor: theme.textSelectionTheme.cursorColor ?? Colors.white,
), ),
) )
: Text(widget.translations.newChatButton); : Text(
widget.translations.newChatButton,
style: theme.appBarTheme.titleTextStyle ??
const TextStyle(
color: Colors.white,
),
);
}
Widget _buildSearchIcon() => IconButton( Widget _buildSearchIcon() {
var theme = Theme.of(context);
return IconButton(
onPressed: () { onPressed: () {
setState(() { setState(() {
_isSearching = !_isSearching; _isSearching = !_isSearching;
query = '';
}); });
if (_isSearching) { if (_isSearching) {
@ -90,8 +176,10 @@ class _NewChatScreenState extends State<NewChatScreen> {
}, },
icon: Icon( icon: Icon(
_isSearching ? Icons.close : Icons.search, _isSearching ? Icons.close : Icons.search,
color: theme.appBarTheme.iconTheme?.color ?? Colors.white,
), ),
); );
}
Widget _buildUserList(List<ChatUserModel> users) { Widget _buildUserList(List<ChatUserModel> users) {
var filteredUsers = users var filteredUsers = users
@ -114,7 +202,9 @@ class _NewChatScreenState extends State<NewChatScreen> {
var user = filteredUsers[index]; var user = filteredUsers[index];
return GestureDetector( return GestureDetector(
child: widget.options.chatRowContainerBuilder( child: widget.options.chatRowContainerBuilder(
ChatRow( Container(
color: Colors.transparent,
child: ChatRow(
avatar: widget.options.userAvatarBuilder( avatar: widget.options.userAvatarBuilder(
user, user,
40.0, 40.0,
@ -122,6 +212,7 @@ class _NewChatScreenState extends State<NewChatScreen> {
title: user.fullName ?? widget.translations.anonymousUser, title: user.fullName ?? widget.translations.anonymousUser,
), ),
), ),
),
onTap: () async { onTap: () async {
await widget.onPressCreateChat(user); await widget.onPressCreateChat(user);
}, },

View file

@ -0,0 +1,67 @@
// SPDX-FileCopyrightText: 2022 Iconica
//
// SPDX-License-Identifier: BSD-3-Clause
import 'package:flutter/material.dart';
import 'package:flutter_chat_view/flutter_chat_view.dart';
class NewGroupChatOverviewScreen extends StatefulWidget {
const NewGroupChatOverviewScreen({
required this.options,
required this.onPressCompleteGroupChatCreation,
required this.service,
required this.users,
this.translations = const ChatTranslations(),
super.key,
});
final ChatOptions options;
final ChatTranslations translations;
final ChatService service;
final List<ChatUserModel> users;
final Function(List<ChatUserModel>, String) onPressCompleteGroupChatCreation;
@override
State<NewGroupChatOverviewScreen> createState() =>
_NewGroupChatOverviewScreenState();
}
class _NewGroupChatOverviewScreenState
extends State<NewGroupChatOverviewScreen> {
final TextEditingController _textEditingController = TextEditingController();
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
iconTheme: theme.appBarTheme.iconTheme ??
const IconThemeData(color: Colors.white),
backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
title: const Text(
'New Group Chat',
style: TextStyle(color: Colors.white),
),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: _textEditingController,
decoration: const InputDecoration(
hintText: 'Group chat name',
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await widget.onPressCompleteGroupChatCreation(
widget.users,
_textEditingController.text,
);
},
child: const Icon(Icons.check_circle),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
);
}
}

View file

@ -0,0 +1,194 @@
// SPDX-License-Identifier: BSD-3-Clause
import 'package:flutter/material.dart';
import 'package:flutter_chat_view/flutter_chat_view.dart';
class NewGroupChatScreen extends StatefulWidget {
const NewGroupChatScreen({
required this.options,
required this.onPressGroupChatOverview,
required this.service,
this.translations = const ChatTranslations(),
super.key,
});
final ChatOptions options;
final ChatTranslations translations;
final ChatService service;
final Function(List<ChatUserModel>) onPressGroupChatOverview;
@override
State<NewGroupChatScreen> createState() => _NewGroupChatScreenState();
}
class _NewGroupChatScreenState extends State<NewGroupChatScreen> {
final FocusNode _textFieldFocusNode = FocusNode();
List<ChatUserModel> selectedUserList = [];
bool _isSearching = false;
String query = '';
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
iconTheme: theme.appBarTheme.iconTheme ??
const IconThemeData(color: Colors.white),
backgroundColor: theme.appBarTheme.backgroundColor ?? Colors.black,
title: _buildSearchField(),
actions: [
_buildSearchIcon(),
],
),
body: FutureBuilder<List<ChatUserModel>>(
// ignore: discarded_futures
future: widget.service.chatUserService.getAllUsers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
return _buildUserList(snapshot.data!);
} else {
return widget.options
.noChatsPlaceholderBuilder(widget.translations);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await widget.onPressGroupChatOverview(selectedUserList);
},
child: const Icon(Icons.arrow_circle_right),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
);
}
Widget _buildSearchField() {
var theme = Theme.of(context);
return _isSearching
? Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextField(
focusNode: _textFieldFocusNode,
onChanged: (value) {
setState(() {
query = value;
});
},
decoration: InputDecoration(
hintText: widget.translations.searchPlaceholder,
hintStyle: theme.inputDecorationTheme.hintStyle ??
const TextStyle(
color: Colors.white,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: theme.inputDecorationTheme.focusedBorder?.borderSide
.color ??
Colors.white,
),
),
),
style: theme.inputDecorationTheme.hintStyle ??
const TextStyle(
color: Colors.white,
),
cursorColor: theme.textSelectionTheme.cursorColor ?? Colors.white,
),
)
: Text(
widget.translations.newGroupChatButton,
style: theme.appBarTheme.titleTextStyle ??
const TextStyle(
color: Colors.white,
),
);
}
Widget _buildSearchIcon() {
var theme = Theme.of(context);
return IconButton(
onPressed: () {
setState(() {
_isSearching = !_isSearching;
query = '';
});
if (_isSearching) {
_textFieldFocusNode.requestFocus();
}
},
icon: Icon(
_isSearching ? Icons.close : Icons.search,
color: theme.appBarTheme.iconTheme?.color ?? Colors.white,
),
);
}
Widget _buildUserList(List<ChatUserModel> users) {
var filteredUsers = users
.where(
(user) =>
user.fullName?.toLowerCase().contains(
query.toLowerCase(),
) ??
false,
)
.toList();
if (filteredUsers.isEmpty) {
return widget.options.noChatsPlaceholderBuilder(widget.translations);
}
return ListView.builder(
itemCount: filteredUsers.length,
itemBuilder: (context, index) {
var user = filteredUsers[index];
var isSelected = selectedUserList.contains(user);
return InkWell(
onTap: () {
setState(() {
if (isSelected) {
selectedUserList.remove(user);
} else {
selectedUserList.add(user);
}
debugPrint('The list of selected users is $selectedUserList');
});
},
child: Container(
color: isSelected ? Colors.amber.shade200 : Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: widget.options.chatRowContainerBuilder(
ChatRow(
avatar: widget.options.userAvatarBuilder(
user,
40.0,
),
title: user.fullName ?? widget.translations.anonymousUser,
),
),
),
if (isSelected)
const Padding(
padding: EdgeInsets.only(right: 16.0),
child: Icon(Icons.check_circle, color: Colors.green),
),
],
),
),
);
},
);
}
}

View file

@ -22,4 +22,13 @@ class ChatProfileService extends ProfileService {
}) { }) {
throw UnimplementedError(); throw UnimplementedError();
} }
@override
FutureOr<bool> changePassword(
BuildContext context,
String currentPassword,
String newPassword,
) {
throw UnimplementedError();
}
} }

View file

@ -4,7 +4,7 @@
name: flutter_chat_view name: flutter_chat_view
description: A standard flutter package. description: A standard flutter package.
version: 1.2.1 version: 1.4.0
publish_to: none publish_to: none
@ -20,15 +20,15 @@ dependencies:
git: git:
url: https://github.com/Iconica-Development/flutter_chat url: https://github.com/Iconica-Development/flutter_chat
path: packages/flutter_chat_interface path: packages/flutter_chat_interface
ref: 1.2.1 ref: 1.4.0
cached_network_image: ^3.2.2 cached_network_image: ^3.2.2
flutter_image_picker: flutter_image_picker:
git: git:
url: https://github.com/Iconica-Development/flutter_image_picker url: https://github.com/Iconica-Development/flutter_image_picker
ref: 1.0.4 ref: 1.0.5
flutter_profile: flutter_profile:
git: git:
ref: 1.1.5 ref: 1.3.0
url: https://github.com/Iconica-Development/flutter_profile url: https://github.com/Iconica-Development/flutter_profile
dev_dependencies: dev_dependencies: