A complete Flutter chat UI kit

Overview

A complete Flutter chat UI kit

pub package

This Flutter package provides you with a base structure as well as a set of tools that allow you to quickly build up a modern chat UI. Instead of trying to come up with all in one Widgets that meet everyone's expectations, you are given helpers that are meant to be used as examples and customized at will.

Features

  • Support for group conversations
  • List of conversations (chats)
  • Group avatar
  • Unread messages badge
  • Message title (user)
  • Message avatar
  • Adaptive message containers depending on relative positioning
  • Controllers with data management api (add, remove, update)
  • Automated selection management
  • Message input with typing events
  • Examples for text, image, audio and video messages

Getting Started

First add the following line to your pubspec.yaml dependencies:

chat_ui_kit: ^[latest_version]

Next, setup your models to extend the base models:

class ChatMessage extends MessageBase {
  //...

  ChatUser author;
  String text;

  @override
  DateTime get createdAt =>
      DateTime.fromMillisecondsSinceEpoch(creationTimestamp);

  @override
  String get id => messageId;

  @override
  String get url => attachment;

  @override
  MessageBaseType get messageType {
    //...
  }
}
class ChatUser extends UserBase {
  //...

  @override
  String get name => username;

  @override
  String get id => userid;

  @override
  String get avatar => avatarURL;
}
class Chat extends ChatBase {
  
  //...

  List<ChatUser> members;
  ChatMessage lastMessage;

  @override
  int get unreadCount => chat.unreadCount;

  @override
  String get name {
    if ((chat?.name ?? null).isNotNullOrEmpty()) return chat.name;
    return membersWithoutSelf.map((e) => e.username).toList().join(", ");
  }

  @override
  String get id => chat?.id;

  @override
  List<ChatUser> get membersWithoutSelf {
    List<ChatUser> membersWithoutSelf = [];
    final localUserId = chat?.localUserId ??
        FirebaseAuth.instance.currentUser?.uid;
    for (ChatUser chatUser in members) {
      if (localUserId != chatUser.userid) membersWithoutSelf.add(chatUser);
    }
    return membersWithoutSelf;
  }
  
}

ChatsListScreen

ChatsListController controller = ChatsListController();

ChatsList(
    controller: _controller,
    appUserId: _currentUser.id,
    scrollHandler: _handleScrollEvent,
    groupAvatarStyle: GroupAvatarStyle(withSeparator: true),
    builders: ChatsListTileBuilders(
        groupAvatarBuilder:
            (context, imageIndex, itemIndex, size, item) {
          final chat = item as Chat;
          return CachedNetworkImage(
              cacheManager: CustomCacheManager(),
              imageUrl: chat.membersWithoutSelf[imageIndex].avatar,
              width: size.width,
              height: size.height,
              fit: BoxFit.cover,
              errorWidget: (ctx, url, val) =>
                  AppErrorWidget(true, size: size));
        },
        lastMessageBuilder: _buildLastMessage,
        wrapper: _buildTileWrapper,
        dateBuilder: (context, date) => Padding(
            padding: EdgeInsets.only(left: 16),
            child: Text(DateFormatter.getVerboseDateTimeRepresentation(
                context, date)))))

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

ChatScreen

final MessagesListController _controller = MessagesListController();

@override
void initState() {
  _controller.selectionEventStream.listen((event) {
    setState(() {
      _selectedItemsCount = event.currentSelectionCount;
    });
  });
  super.initState();
}

Widget _buildMessagesList() {
  IncomingMessageTileBuilders incomingBuilders = _isGroupChat
      ? IncomingMessageTileBuilders(
          bodyBuilder: (context, index, item, messagePosition) =>
              _buildMessageBody(context, index, item, messagePosition,
                  MessageFlow.incoming),
          avatarBuilder: (context, index, item, messagePosition) {
            final _chatMessage = item as ChatMessage;
            return Padding(
                padding:
                    EdgeInsets.only(right: 16),
                child: _buildAvatarWithScore(_chatMessage.author));
          })
      : IncomingMessageTileBuilders(
          bodyBuilder: (context, index, item, messagePosition) =>
              _buildMessageBody(context, index, item, messagePosition,
                  MessageFlow.incoming),
          titleBuilder: null);

  return Expanded(
      child: MessagesList(
          controller: _controller,
          appUserId: _currentUser.id,
          useCustomTile: (i, item, pos) {
            final msg = item as ChatMessage;
            return msg.isTypeEvent;
          },
          messagePosition: _messagePosition,
          builders: MessageTileBuilders(
              customTileBuilder: _buildEventMessage,
              customDateBuilder: _buildDate,
              incomingMessageBuilders: incomingBuilders,
              outgoingMessageBuilders: OutgoingMessageTileBuilders(
                  bodyBuilder: (context, index, item, messagePosition) =>
                      _buildMessageBody(context, index, item,
                          messagePosition, MessageFlow.outgoing)))));
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

More

Please make sure to browse the class inlined documentation before asking any questions. PRs are very welcome!

Comments
  • ChatListController how to update when stream update?

    ChatListController how to update when stream update?

    Hi, to clarify my question, I'll post code in case being missunderstand.

    Now I am using this way to add list to _mode.controller:

    widget.chatBloc.chatWithMembers.listen((event) {
          gLogger.i("chatWithMembers: $event");
          // _model.controller.notifyChanges();
          _model.controller.addAll(event);
        });
    

    This works on first init load which addAll list. But when I update the list order in stream, (only update order, not insert or add any items). the stream will update right? But there addAll will add all again. But I just need update. So that the list will add twice.

    My question is, currently ChatListController only have a addAll function, how to update the order anyway? If it have .clear() then I can just clear and addAll, but currently not same as List in dart. What should users do in this siutation?

    opened by jinfagang 9
  • [feature] Add a bar widget to ChatList

    [feature] Add a bar widget to ChatList

    Hi, what to do if I want add a status bar (a container with a text in center of it indicates connection of chat). How to do it for now?

    I tried stack ChatList inside Column, the widget tree will broken.

    opened by jinfagang 7
  • How to work with Bloc?

    How to work with Bloc?

    Hi, take your example code as example:

    return ChatsList(
            chatsListStyle: ChatsListStyle(physics: BouncingScrollPhysics()),
            controller: _model.controller,
            appUserId: _model.localUser.id,
            scrollHandler: handleScrollEvent,
            groupAvatarStyle: GroupAvatarStyle(
                withSeparator: false,
                separatorColor: Colors.white,
                mode: GroupAvatarMode.aligned),
            builders: ChatsListTileBuilders(
                groupAvatarBuilder: (context, imageIndex, itemIndex, size, item) {
                  final chat = item as ChatWithMembers;
                  return Image.asset(chat.membersWithoutSelf[imageIndex].avatar,
                      width: size.width, height: size.height, fit: BoxFit.cover);
                },
                lastMessageBuilder: _buildLastMessage,
                wrapper: _buildTileWrapper,
                dateBuilder: (context, date) => Padding(
                    padding: EdgeInsets.only(left: 16),
                    child: Text(DateFormatter.getVerboseDateTimeRepresentation(
                        context, date)))),
            areItemsTheSame: (ChatBase oldItem, ChatBase newItem) =>
                oldItem.id == newItem.id);
    

    the chats is controlled inside controller: _model.controller, right? Then my question is, how to make it work with bloc stream?

    I mean, typically using a StreamBuilder and a stream from my bloc to feed data into this controller, is there way to make this happen?

    opened by jinfagang 7
  • MessagesListController not able to clear items when enter chatPage again from another chatid

    MessagesListController not able to clear items when enter chatPage again from another chatid

    Here is my code:

    gLogger.i("init controller items: ${_controller.items.length}");
        _controller.items.clear();
        _controller.notifyChanges();
        _chatBloc.fetchLocalMsgsForSession(_chat.id);
        subscription = _chatBloc.crtChatMsgs.listen((event) {
          _controller.addAll(event);
          _controller.notifyChanges();
          gLogger.i("now controller items: ${_controller.items.length}");
        });
    

    this is inside my initState function, so I want clear items every time enter a new chatPage. But it doesn't do this.

    Normally, first log should be 0, and every time crtChatMsgs only fetechs 25 msgs from local. So everytime it enters chatPage, it should be 25 msgs.

    However, first time:

    image

    this is normal, then I switch to another chatid (another chat page):

    image

    As u can see, second time the msg doesn't clear at all. It becomes 50, double of them. Normally, it should be fresh 25 msgs.

    And the UI actually doesn't updated still contains data from previous chatid.

    What could be the reason?

    (I am new to flutter maybe I did something wrong but this lib is really useful, so I use it)

    opened by luohao123 6
  • Avatar from network

    Avatar from network

    Hi,

    Thanks for open sourcing this kit. I was wondering if it supports loading images from a network. I couldn't get that to work. Is there some widget that could be extended or something? Thanks.

    opened by jc324 5
  • [feature] Add the padding to ImplicitlyAnimatedList

    [feature] Add the padding to ImplicitlyAnimatedList

    https://github.com/bnxm/implicitly_animated_reorderable_list/issues/77#issuecomment-853332816

    After a long discussion with this lib author, it seems can set the padding value to ImplicitlyAnimatedList. My proposal is can you consider expose this params out so that users can choose to set it or not? thanks.

    opened by jinfagang 5
  • ChatsList don't like listview behavior

    ChatsList don't like listview behavior

    this is normal ListView:

    image

    this is ChatsList image

    Hi, I am not here report a bug or problem of this package. On the opposite using this lib I managed to build a useful chat App.

    But I found a slightly bias behavior might not notice by you. As you can see, when the List scroll to the bottom, ChatsList can not handle with the bottomBar, while ListView can handle, on the other words, ListView the last item will not blind by the navigationBar, this can be notice easily if your bottomBar blurred.

    Is there a way to replace ChatsList with ListView while also preserve all other features? I really don't know why they behavior such bias

    invalid 
    opened by jinfagang 5
  • Please upgrade just_audio pub requirements

    Please upgrade just_audio pub requirements

    It's too low and some basic package will conflict:

    and just_audio >=0.3.0 <0.7.0-nullsafety.0 then image >=2.1.18 <3.0.0-nullsafety.0.
    And because chat_ui_kit >=1.1.5 depends on just_audio ^0.6.13 and image >=2.1.14 <3.0.0-nullsafety.0 depends on xml ^4.2.0, if karyo from git and chat_ui_kit >=1.1.5 then xml ^4.2.0.
    

    Some mordern pakcage already using latest package. But just_audio inside this repo doesn't update yet.

    It still needs some lower basic lib which conficts with other mordern lib

    opened by jinfagang 5
  • [feature request] Stylizing message input

    [feature request] Stylizing message input

    There is no mention of stylizing the input provided with the library, even digging through the code it is apparent that this is not yet implemented link. Thank you

    opened by Dreamersoul 4
  • [Feature] Mark Message as

    [Feature] Mark Message as

    Hi Your library is so great ! thank you so much to share it.

    Use case:

    1. User want to reply to a message
    2. User want to modify his own message

    For use case 2, im using existing API on controller https://github.com/themadmrj/chat_ui_kit/blob/3d03ae5de83906d01a4cd78bff2758be2397a0c2/lib/src/utils/controllers.dart#L100

    The process is : Mark a message > Update the UI > When a message is send > Detect if a message is marked > Update database according to

    It enable me, to update the UI (show the old message on top of the submit form). When user is done, i unselect

    selectis a great way to select multiple messages once, and make something on them. But we need also, a markAsModify, markAsReply to make the controller more complete.

    void mark(T item, String family) {
        _markItems[family] = item;
        notifyListeners();
        _controller.sink.add(****);
      } 
    
    opened by Abacaxi-Nelson 4
  • lastMessage must be non null

    lastMessage must be non null

    opened by Abacaxi-Nelson 4
  • Dependency flutter_video_info is not working in android 33

    Dependency flutter_video_info is not working in android 33

    Hello there,

    I found out chat_ui_kit error during compilation for device with android 33. This package flutter_video_info is the main culprit and seems not maintain by the developer anymore. Any plan to replace/remove it?

    Thanks

    opened by devianl2 0
  • Isolate Error from Implicitly_animated_list

    Isolate Error from Implicitly_animated_list

    Hello, i'm using your plugin since early this year. but i found an error, it happened in chat list and i think that because of implicitly_animated_list plugin. and error appeared if i have 39+ items in chat list.

    This is the error from my console log :

    E/flutter ( 5273): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message: (object extends NativeWrapper - Library:'dart:io' Class: _RandomAccessFileOpsImpl@13069316) E/flutter ( 5273): #0 Isolate._spawnFunction (dart:isolate-patch/isolate_patch.dart:395:25) E/flutter ( 5273): #1 Isolate.spawn (dart:isolate-patch/isolate_patch.dart:375:7) E/flutter ( 5273): #2 compute package:flutter/…/foundation/_isolates_io.dart:22 E/flutter ( 5273): #3 MyersDiff.diff package:implicitly_animated_reorderable_list/…/diff/myers_diff.dart:47 E/flutter ( 5273): #4 MyersDiff.withCallback package:implicitly_animated_reorderable_list/…/diff/myers_diff.dart:24

    and this is my UI with 39+ items in list, when i refresh the ui / set state, the error will appear. image

    Thanks before :)

    opened by asfarul 2
Releases(1.1.0)
Owner
Self-taught, I mainly create or contribute to Flutter packages and plugins.
null
Flutter-Shop-UI-Kit - Create An E-commerce App UI kit Using Flutter

Flutter Shop UI kit If you are planning to create an e-commerce app using Flutte

Abu Anwar 405 Dec 28, 2022
It is a simple group chat application made with flutter back-end by Firebase. People can chat like a community chat.

flash_chat A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Moideen Rafih P A 4 Aug 7, 2022
A powerful Flutter chat UI component library and business logic for Tencent Cloud Chat, creating seamless in-app chat modules for delightful user experiences.

<style> .button-9 { appearance: button; backface-visibility: hidden; background-color: #1d52d9; border-radius: 6px; border-width: 0; box-shadow: rgba(

Tencent Cloud 63 Aug 11, 2023
Chat-application - Build Chat Application using Flutter and Firebase

Build Chat Application using Flutter & Firebase Source Code - Enjoy ! Social Med

Muhammad Irvan 0 Jan 3, 2022
Chat-App - A Chat App with flutter and Firebase and Video Calling using WebRTC

chat_app A chat app with flutter and firebase with image message support and vid

Reza Hosseinypour 10 Nov 23, 2022
Amir Khan 47 Jan 8, 2023
A Flutter Starter Kit (Boilerplate) to kick-start your next Android and iOS app

Flutter Starter Kit (Boilerplate) using the BLoC Pattern A Flutter starter application that utilizes the BLoC Pattern. You can read more at this Mediu

AceLords 233 Dec 28, 2022
A Flutter IM Kit

flutter_im_kit 概述 flutter_im_kit 是一套基于 Flutter 的 IM 组件库,提供 IM 业务场景下的常用 UI 组件和解决方案。 组件集合 flutter_excellent_badge 常用于消息提醒的红点展示。 BadgePosition 用于设置 flutt

Teren 6 Jul 27, 2022
A flutter ffmpeg kit example

flutter-ffmpeg-kit-lts-repro Steps to reproduce: git clone [email protected]:jozsefsallai/flutter-ffmpeg-kit-lts-repro.git cd flutter-ffmpeg-kit-lts-repr

József Sallai 1 Mar 5, 2022
🍔😋 Grocery Shopping App template UI kit in Flutter

?? ?? Fryo - Grocery Shopping App template kit A Flutter UI template of a Grocery Shopping App I found on Uplabs. Design screens are on Uplabs. It's p

Victor Aremu 490 Jan 3, 2023
A Translator App Which is Build using Flutter, Speech To Text, Google ML Kit, Google Translator and Text To Speech.

AI Translator This is a Translator App Which is Build using Flutter, Speech To Text, Google ML Kit, Google Translator and Text To Speech. Download App

null 4 Jul 16, 2022
An App I made to learn of FIrebase Phone Auth and ML Kit

demoapp A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

D Srikhar Shashi 1 Oct 19, 2021
With ML Kit's face detection API, you can detect faces in an camera or image, Note that the API detects faces, it does not recognize people

Face Detection This project is a starting point for a Flutter application. Getting Started For help getting started with Flutter, view our online docu

Nashwan Abdullah 21 Dec 29, 2022
Flutter App Developer Roadmap - A complete roadmap to learn Flutter App Development

Flutter App Developer Roadmap - A complete roadmap to learn Flutter App Development. I tried to learn flutter using this roadmap. If you want to add something please contribute to the project. Happy Learning

Md Tarikul Islam 708 Jan 3, 2023
GetDoctor is a complete app developed in Flutter, Firebase and Blazor,.Net Core API and SQL Server

GetDoctor ?? ?? ?? GetDoctor is a complete app developed in Flutter, Firebase and Blazor,DotNet Core API and SQL Server GetDoctor is a complete packag

Sunil Vijayan 69 Dec 19, 2022
A complete grocery store developed with Flutter, .Net Core, Firebase, One Signal and SQL Server as backend

# Grocery-Store developed in Flutter,DotNet Core, Firebase, One-Signal, SQL-Server, Stripe, Razorpay, Paypal A complete grocery store developed with F

Sunil Vijayan 31 Jan 1, 2023
Complete Flutter OpenIdConnect Library

OpenIdConnect for Flutter Standards compliant OpenIdConnect library for flutter that supports: Code flow with PKCE (the evolution of implicit flow). T

null 50 Dec 24, 2022
A complete Flutter E-Commerce Book Store application built using firebase as backend

ecommerce A complete Flutter E-Commerce Book Store application built using firebase as backend. Features Add or remove item in cart Search products Ad

aakanksha 2 Sep 24, 2022
A Complete Weather App Using Flutter

weather ?? A complete weather app Use this source code in your project Rate me ⭐ Thank you ☺ Platform Android ✔️ Preview About Work it with API Finde

Amirziya 3 May 18, 2022