Flutter即时通讯插件chating的使用

Flutter即时通讯插件chating的使用

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

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:
    • <code>context</code>: The BuildContext of the widget.
    • <code>index</code>: 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:
    • <code>context</code>: The BuildContext for the widget.
    • <code>index</code>: 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(
        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

  • <code>text</code>
    • The message content.
    • Example: 'Hello World!'.
  • <code>date</code>
    • The timestamp of the message.
    • Example: '12:00 PM'.
  • <code>isSender</code>
    • A boolean value indicating whether the message was sent by the user (true) or received from another participant (false).
    • Example: true.
  • <code>sent</code>
    • 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

  • <code>id</code>
    • A unique identifier for the image message.
    • Example: '123'.
  • <code>image</code>
    • A widget representing the image content.
    • Typically loaded using constructors like Image.network, Image.asset, etc.
    • Example:
    Image.network('https://via.placeholder.com/150')
    
  • <code>date</code>
    • A string representing the timestamp of the message.
    • Example: '12:00 PM'.
  • <code>isSender</code>
    • A boolean indicating whether the message was sent by the user (true) or received from another participant (false).
    • Example: false.
  • <code>sent</code>
    • 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.


Constant

All API requests use the following base URL:

BaseUrl: http://95.179.242.182:6014

Get api key and platform id from integration team

X-PLATFORM-ID :
X-API-KEY :

Package Required

Add the following package to your pubspec.yaml:

signalr_netcore: last version
retrofit: last version

use retrofit

part 'client.g.dart';

@RestApi(baseUrl: '${baseUrl}')
abstract class RestClient {
  factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
}

login

[@POST](/user/POST)('/authentication/user-platform-login')
Future<AuthModel> login(
  @Header('X-PLATFORM-ID') String platformId,
  @Header('X-API-KEY') String key,
  @Body() LoginRequestModel body
);

model

class LoginRequestModel {
    final String userId;
    final String name;
    final int phoneNumber;
}

SignalR Integration

    SignalR signlR = SignalR(baseUrl: baseUrl, token: token); // initialize 
    signlR.onReceiveMessage(callback: (data){});
    signlR.startConnection(); // if you need to start the connection
    signlR.stopConnection(); // end connection 

Get Chats From API

  @GET('/chats')
  Future<ChatsModel> getChats();

navigate to chat

  @GET('/chats/$chatId/token')
  Future<ChatTokenModel> navigate(
    @Path('chatId') String chatId,
    @Query('senderId') String? senderId,
  );

new chat api

  [@POST](/user/POST)('/chats')
  Future<ChatTokenModel> newChat(
    @Header('X-PLATFORM-ID') String platformId,
    @Header('X-API-KEY') String key,
    @Body() NewChatModelRequest body
  );
  

model

class NewChatModelRequest {
    final String senderName;
    final int senderPhoneNumber;
    final String senderPlatformUserId;
    final String receiverName;
    final int receiverPhoneNumber;
    final String receiverPlatformUserId
}

get message for this chat

  @GET('/chats/messages')
  Future<MessageModel> getMessage(
    @Query('Page') int page
    @Query('PageSize') int pageSize
  );

send message

  [@POST](/user/POST)('/messages')
  [@Multipart](/user/Multipart)
  Future<Response> sendMessage({
    @Part(name : 'text') required String text,
    @Part(name : 'File') required MultipartFile file,
  });

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用即时通讯插件 chating 的代码示例。请注意,chating 并非一个广为人知的Flutter插件,因此我假设你提到的 chating 插件可能是一个自定义的或者假想的插件,用于展示如何在Flutter中实现即时通讯功能。如果 chating 插件真实存在,请参考其官方文档以获取准确的使用指南。

在这个示例中,我将展示如何创建一个简单的即时通讯界面,并使用一个假想的 chating 插件来发送和接收消息。如果 chating 插件不存在,你可以考虑使用如 firebase_messagingsocket_io_client 等流行的即时通讯插件。

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 chating 插件的依赖(如果它存在)。如果它不存在,你可以使用其他类似的插件,比如 firebase_messaging

dependencies:
  flutter:
    sdk: flutter
  chating: ^x.y.z  # 假设 chating 插件的版本是 x.y.z

2. 初始化插件

在你的 main.dart 文件中初始化插件。

import 'package:flutter/material.dart';
import 'package:chating/chating.dart';  // 假设 chating 插件的导入路径是这样的

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化 chating 插件(如果插件需要初始化)
  Chating.initialize();
  runApp(MyApp());
}

3. 创建聊天界面

创建一个简单的聊天界面,包含消息输入框和消息列表。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _controller = TextEditingController();
  final List<String> _messages = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_messages[index]),
                );
              },
            ),
          ),
          Divider(),
          Container(
            decoration: BoxDecoration(
              color: Colors.grey[200],
              padding: EdgeInsets.symmetric(horizontal: 8.0),
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () {
                    _sendMessage();
                    _controller.clear();
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _sendMessage() {
    String message = _controller.text;
    // 使用 chating 插件发送消息(假设插件有 sendMessage 方法)
    Chating.sendMessage(message).then((response) {
      // 处理发送消息后的响应(例如,将消息添加到本地消息列表)
      setState(() {
        _messages.add(message);
      });
    }).catchError((error) {
      // 处理发送消息时的错误
      print('Error sending message: $error');
    });
  }
}

4. 监听接收消息

通常,即时通讯插件会提供一个方法来监听接收到的消息。在这个示例中,我们假设 chating 插件有一个 onMessageReceived 方法。

@override
void initState() {
  super.initState();
  // 监听接收到的消息
  Chating.onMessageReceived.listen((message) {
    setState(() {
      _messages.add(message);
    });
  });
}

5. 完整代码

将上述代码片段整合到一个完整的 main.dart 文件中。

import 'package:flutter/material.dart';
import 'package:chating/chating.dart';  // 假设 chating 插件的导入路径是这样的

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Chating.initialize();  // 初始化 chating 插件(如果插件需要初始化)
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _controller = TextEditingController();
  final List<String> _messages = [];

  @override
  void initState() {
    super.initState();
    // 监听接收到的消息
    Chating.onMessageReceived.listen((message) {
      setState(() {
        _messages.add(message);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chat'),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_messages[index]),
                );
              },
            ),
          ),
          Divider(),
          Container(
            decoration: BoxDecoration(
              color: Colors.grey[200],
              padding: EdgeInsets.symmetric(horizontal: 8.0),
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () {
                    _sendMessage();
                    _controller.clear();
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _sendMessage() {
    String message = _controller.text;
    Chating.sendMessage(message).then((response) {
      setState(() {
        _messages.add(message);
      });
    }).catchError((error) {
      print('Error sending message: $error');
    });
  }
}

请注意,上述代码是基于一个假设的 chating 插件。如果 chating 插件不存在或功能不同,请查阅相应的插件文档并根据实际情况调整代码。如果你正在寻找一个实际可用的即时通讯插件,可以考虑使用 firebase_messagingsocket_io_client 或其他流行的Flutter即时通讯插件。

回到顶部