chating 1.0.1 copy "chating: ^1.0.1" to clipboard
chating: ^1.0.1 copied to clipboard

A customizable chat UI library for Flutter.

Chat SDK #

I created a chat library to help you build chat systems quickly and easily, with ready-to-use tools that save time and effort. #

N|Solid

Build Status

chatsList #


ChatsList(
          title: 'chats',
          itemCount: getChats(),
          refreshController: refreshController,
          onRefresh: () async {
            await loadingNewChat(hasNext: true);
          },
          itemBuilder: (BuildContext context, int index) {
            return const ListTile(
              title: Text('Ali Jassib'),
              subtitle: Text('Hello, How are you?'),
              trailing: Icon(Icons.arrow_forward_ios),
            );
          },
        ),

Parameters #

title #

  • A string that represents the title or heading of the chat list.
  • Example: 'chats'.

itemCount #

  • Defines the total number of chat items to be displayed in the list.
  • This value is dynamically retrieved using the getChats() function.

refreshController #

  • Manages the pull-to-refresh functionality.
  • Used with libraries like pull_to_refresh to allow users to refresh the chat list.

onRefresh #

  • A callback function triggered when the user performs a pull-to-refresh action.
  • Example: Calls the loadingNewChat(hasNext: true) function to load additional chat data asynchronously.

itemBuilder #

  • A function responsible for building each chat item in the list.
  • Parameters:
    • context: The BuildContext of the widget.
    • index: The index of the current chat item.

Chat #

Chat(
          title: 'Ali Jassib',
          refreshController: refreshController,
          itemCount: getMessages(),
          onRefresh: () async{
            await loadingNewMessage(hasNext: true);
          },
          scrollController: scrollController,
          inputWidget: inputWidget,
          itemBuilder: (context, index) {
            return messageCard(index);
          },
        ),

Parameters #

title #

  • A string that represents the title of the chat.
  • Example: 'Ali Jassib'.

refreshController #

  • Manages the state of the pull-to-refresh functionality.
  • Used with libraries like pull_to_refresh to allow users to refresh the chat messages.

itemCount #

  • Specifies the total number of messages to display.
  • This value is dynamically fetched using the getMessages() function.

onRefresh #

  • A callback function triggered when the user performs a pull-to-refresh action.
  • Example: Calls the loadingNewMessage(hasNext: true) function to fetch new messages asynchronously.

scrollController #

  • Controls the scrolling behavior of the chat view.
  • Useful for programmatically scrolling to a specific position or managing the user's scroll actions.

inputWidget #

  • A widget that handles user input for sending messages.
  • Example: A custom input field or toolbar widget.

itemBuilder #

  • A function responsible for rendering each message in the chat view.
  • Parameters:
    • context: The BuildContext for the widget.
    • index: The index of the current message being rendered.

Full Example for chat list widget #

We provided you with a set of classes to simplify the task of building your UI efficiently and effortlessly.:

import 'package:chating/chating.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Chat UI Example')),
        body: ChatsList(
          title: 'chats',
          itemCount: getChats(),
          refreshController: refreshController,
          onRefresh: () async {
            await loadingNewChat(hasNext: true);
          },
          itemBuilder: (BuildContext context, int index) {
            return const ListTile(
              title: Text('Ali Jassib'),
              subtitle: Text('Hello, How are you?'),
              trailing: Icon(Icons.arrow_forward_ios),
            );
          },
        ),
      ),
    );
  }

  RefreshController get refreshController => RefreshController();

  Future<void> loadingNewChat({required bool hasNext}) async {
    if (hasNext) {
      // write your logic code here
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  // Here, you can later add the model you receive from the backend and set it up in this spot so you can use and inject it into the UI seamlessly.
  int getChats() {
    // write your logic code here
    return 10;
  }
}

MessageCard & ImageCard Widgets #

The MessageCard and ImageCard widgets are designed for chat applications to represent individual text or image messages. Both widgets are customizable and can be tailored to fit various chat designs.


MessageCard Widget #

The MessageCard widget is used to display a text message in the chat.

Parameters #

  • text

    • The message content.
    • Example: 'Hello World!'.
  • date

    • The timestamp of the message.
    • Example: '12:00 PM'.
  • isSender

    • A boolean value indicating whether the message was sent by the user (true) or received from another participant (false).
    • Example: true.
  • sent

    • A boolean value that indicates if the message was successfully sent (true) or is pending (false).
    • Example: true.

Example Usage #

const MessageCard(
  text: 'Hello World!',
  date: '12:00 PM',
  isSender: true,
  sent: true,
);

ImageCard Widget #

The ImageCard widget is designed to display an image message in a chat interface. It includes properties for customization, such as the image source, message metadata, and sender information.

Parameters #

  • id

    • A unique identifier for the image message.
    • Example: '123'.
  • image

    • A widget representing the image content.
    • Typically loaded using constructors like Image.network, Image.asset, etc.
    • Example:
      Image.network('https://via.placeholder.com/150')
      
  • date

    • A string representing the timestamp of the message.
    • Example: '12:00 PM'.
  • isSender

    • A boolean indicating whether the message was sent by the user (true) or received from another participant (false).
    • Example: false.
  • sent

    • A boolean indicating whether the image message was successfully sent (true) or is pending (false).
    • Example: true.

Example Usage #

ImageCard(
  id: '123',
  image: Image.network('https://via.placeholder.com/150'),
  date: '12:00 PM',
  isSender: false,
  sent: true,
);

Full Example for chat widget #

To start a chat with someone and begin the conversation, the UI will look like this:

import 'dart:math';

import 'package:chating/chating.dart';
import 'package:chating/src/components/custom_typing_card.dart';
import 'package:chating/src/components/image_card.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Chat(
          title: 'Ali Jassib',
          refreshController: refreshController,
          itemCount: getMessages(),
          onRefresh: () async{
            await loadingNewMessage(hasNext: true);
          },
          scrollController: scrollController,
          inputWidget: inputWidget,
          itemBuilder: (context, index) {
            return messageCard(index);
          },
        ),
      ),
    );
  }

  RefreshController get refreshController => RefreshController();
  ScrollController get scrollController => ScrollController();
  TextEditingController get textController => TextEditingController();


  // Here, you can later add the model you receive from the backend and set it up in this spot so you can use and inject it into the UI seamlessly.
  int getMessages() {
    return 10;
  }

  Future<void> loadingNewMessage({bool hasNext = false}) async {
     if (hasNext) {
      // write your logic code here
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  Widget get inputWidget => CustomTypingCard(
        textController: textController,
        scrollController: scrollController,
        onSend: () {
          // Send message logic or call the function to send the message
        },
        onTapImageUpload: () {
          // Image upload logic or call the function to upload the image
        },
        iconSend: const Icon(Icons.send),
        hintText: 'Type a message',
      );

Backend Integration #

This document provides a detailed guide to integrating backend services for a chat application, including real-time SignalR connections, user authentication, chat management, and message handling.


Base URL #

All API requests use the following base URL:
http://95.179.242.182:6014


SignalR Integration #

Package Required #

Add the following package to your pubspec.yaml:

signalr_netcore: last version

SignlR Connecting #

NOTI String baseUrls = 'http://95.179.242.182:6014' NOTI signalr_netcore: ^1.3.6 this is package

connects() {
    connection = HubConnectionBuilder()
        .withUrl(
          'http://95.179.242.182:6014/hubs/chats?access_token=${token here}',
        )
        .withAutomaticReconnect(retryDelays: [0, 1000, 5000, 10000, 20000, 30000])
        .withHubProtocol(JsonHubProtocol())
        .build();

    connection.on("ReceiveMessage", (data) {
      Logger().d("Data: $data");
      chatController.receiveMessage(data);
    });

    Logger().d("Connection started");
  }

  Future startConnection() async {
    await connection.start();
    Logger().d("[SIGNALR] Connection started");
  }

  Future stopConnection() async {
    await connection.stop();
    Logger().d("[SIGNALR] Connection stopped");
  }

login #

Future<void> login({
  required String platformID,
  required String keyID,
  required String userID,
  required String name,
  required String phoneNumber,
}) async {
  try {

    var response = await Dio().post('$base_URL/authentication/user-platform-login',
      options: Options(headers: {
        'X-PLATFORM-ID': platformID,
        'X-API-KEY': keyID,
      }),
      data: {
        "userId": userID,
        "name": name,
        "phoneNumber": phoneNumber,
      },
    );

    if (response.statusCode == 200) {
     // your logic here
    } else {
      print('Login failed: ${response.statusCode}');
    }
  } catch (e) {
    print('Error during login: $e');
  } finally {
   // your logic here
  }
}

Get Chats From API #

Future<void> getChats() async {
  try {
    var response = await Dio().get('$base_URL/chats');
    if (response.statusCode == 200) {
     // your logic here
    } else {
      print('Failed to fetch chats: ${response.statusCode}');
    }
  } catch (e) {
    print('Error fetching chats: $e');
  } finally {
    // your logic here
  }
}
Future<void> navigate({required String chatId, String? senderId}) async {
    // we use senderId if we want to open new chat
    var response = await Dio().get(api: '$base_URL/chats/$chatId/token',
      queryParameters: {
        'senderId': senderId // can be null,
      },
    );
    if (response != null) {
     your logic here
    }
  }

new chat api #

 Future newChat({
    required String platformID,
    required String keyID,
    required String senderPlatformUserID,
    required String senderPhoneNumber,
    required String senderName,
    required String receiverPlatformUserID,
    required String receiverPhoneNumber,
    required String receiverName,
  }) async {
   
    var response = await Dio().post(
        api: '$base_URL/chats',
        options: dio.Options(followRedirects: false, validateStatus: (status) => status! < 500, headers: {
          'X-PLATFORM-ID': platformID,
          'X-API-KEY': keyID,
        }),
        data: {
          "senderName": senderName,
          "senderPhoneNumber": senderPhoneNumber,
          "senderPlatformUserId": senderPlatformUserID,
          "receiverName": receiverName,
          "receiverPhoneNumber": receiverPhoneNumber,
          "receiverPlatformUserId": receiverPlatformUserID,
        });
    if (response.item1) {
     // your login here
    }
   
  }

get message for this chat #

 Future<void> getMessages() async {
    var response = await Dio().get(api: '$base_URL/chats/messages', queryParameters: {
      'Page':  1,
      'PageSize': 50,
    });
    if (response != null) {
      // your login here
    }
  }

send message #

 Future<void> sendMessage({required String text, required String chatId, File? image}) async {
    var response = await Dio().post(
      api: '$base_URL/messages',
      data: FormData.fromMap({
        "text": text.isEmpty ? null : text,
        'File': image != null ? await dio.MultipartFile.fromFile(image.path) : null,
      }),
    );
    if (response.item1) {
    // your logic here
    }
  }
4
likes
0
points
563
downloads

Publisher

unverified uploader

Weekly Downloads

A customizable chat UI library for Flutter.

Homepage

License

unknown (license)

Dependencies

flutter, intl, pull_to_refresh

More

Packages that depend on chating