swift_chat 1.1.1 copy "swift_chat: ^1.1.1" to clipboard
swift_chat: ^1.1.1 copied to clipboard

A highly customizable and easy-to-use chat UI package for Flutter. It provides a complete chat screen designed to be powered by a real-time backend like WebSockets.

SwiftChat: A Real-Time Chat UI for FlutterA highly customizable and easy-to-use chat UI package for Flutter. SwiftChat provides a complete, responsive chat screen designed to be powered by a real-time backend like WebSockets, making it simple to build modern chat applications.Features💬 Complete Chat UI: A beautiful, pre-built chat screen with message bubbles and a message composer.🔌 Backend Agnostic: Designed to work with any WebSocket backend via a simple stream-based architecture.🎨 Highly Customizable: Easily change colors, text styles, and input decorations using the SwiftChatTheme class.🚀 Lightweight & Performant: Built with a focus on performance and a minimal footprint.📱 Responsive Design: Adapts gracefully to different screen sizes and orientations.1. Flutter App ImplementationThis section guides you through integrating and using the SwiftChat widget in your Flutter application.InstallationAdd the following to your pubspec.yaml file. You will also need web_socket_channel to communicate with your server.dependencies: flutter: sdk: flutter swift_chat: ^1.1.0 # Use the latest version from pub.dev web_socket_channel: ^2.4.0 # For WebSocket communication Then, run flutter pub get in your terminal.Code UsageHere is a complete, well-commented example of a chat screen.import 'package:flutter/material.dart'; import 'package:swift_chat/swift_chat.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'dart:convert'; import 'dart:math';

void main() => runApp(const MyApp());

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

@override Widget build(BuildContext context) { return const MaterialApp( title: 'SwiftChat Demo', home: ChatScreen(), ); } }

class ChatScreen extends StatefulWidget { const ChatScreen({super.key});

@override State

class _ChatScreenState extends State

// 2. MANAGE THE LIST OF MESSAGES final List

// 3. ESTABLISH THE WEBSOCKET CONNECTION // Replace 'localhost' with your server's IP address. // Use 'ws://localhost:8080' for the Node.js server. // Use 'ws://localhost:8765' for the Python server. final _channel = WebSocketChannel.connect( Uri.parse('ws://localhost:8080'), );

@override void initState() { super.initState(); // 4. LISTEN FOR INCOMING MESSAGES _channel.stream.listen((data) { final decodedData = jsonDecode(data);

  // Create a ChatUser and ChatMessage from the received data
  final user = ChatUser(
    id: decodedData['userId'],
    name: decodedData['userName'],
  );
  final incomingMessage = ChatMessage(
    id: decodedData['id'],
    text: decodedData['text'],
    user: user,
    createdAt: DateTime.parse(decodedData['createdAt']),
  );

  // Add the message to the list and update the UI
  if (mounted) {
    setState(() {
      _messages.add(incomingMessage);
    });
  }
});

}

// 5. HANDLE SENDING MESSAGES void handleSend(String text) { // Create a new message object final message = ChatMessage( id: 'msg${Random().nextInt(9999)}', text: text, user: _currentUser, createdAt: DateTime.now(), );

// Add the message to the UI immediately for a responsive feel
setState(() {
  _messages.add(message);
});

// Prepare the data to be sent to the server
final messageData = {
  'id': message.id,
  'text': message.text,
  'userId': message.user.id,
  'userName': message.user.name,
  'createdAt': message.createdAt.toIso8601String(),
};

// Send the JSON-encoded message to the WebSocket server
_channel.sink.add(jsonEncode(messageData));

}

@override void dispose() { // 6. CLOSE THE CONNECTION _channel.sink.close(); super.dispose(); }

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Global Chat Room'), ), // 7. USE THE SWIFTCHAT WIDGET body: SwiftChat( currentUser: _currentUser, messages: _messages, onSend: _handleSend, // Optional: Customize the theme theme: const SwiftChatTheme( primaryBubbleColor: Colors.deepPurple, secondaryBubbleColor: Color(0xFFF0F0F0), sendButtonColor: Colors.deepPurple, ), ), ); } } 2. Backend Implementation GuideSwiftChat requires a WebSocket server to function. The server's only job is to broadcast any message it receives to all other connected clients. Here’s how to build one in Node.js and Python.Message Data StructureAll communication between the client and server should use the following JSON format:{ "id": "msg_123", "text": "Hello everyone!", "userId": "user_abc", "userName": "Alice", "createdAt": "2025-08-24T18:30:00.000Z" } Node.js BackendThis implementation uses the lightweight ws library.Setup:# Create a new project directory mkdir swiftchat-server-node cd swiftchat-server-node

Initialize a Node.js project #

npm init -y

Install the WebSocket library #

npm install ws server.js:const { WebSocket, WebSocketServer } = require('ws');

// Create a WebSocket server on port 8080 const wss = new WebSocketServer({ port: 8080 });

console.log('Server is running on ws://localhost:8080');

// This event fires when a new client connects wss.on('connection', function connection(ws) { console.log('A new client has connected.');

// This event fires when the server receives a message from a client ws.on('message', function message(data) { console.log('Received message: %s', data);

// Broadcast the received message to all connected clients
wss.clients.forEach(function each(client) {
  if (client.readyState === WebSocket.OPEN) {
    client.send(data.toString());
  }
});

});

ws.on('close', () => { console.log('A client has disconnected.'); });

ws.send('Welcome to the chat!'); }); Run the server:node server.js Python BackendThis implementation uses the standard websockets library with asyncio.Setup:# Create a new project directory mkdir swiftchat-server-python cd swiftchat-server-python

Create a virtual environment (recommended) #

python -m venv venv source venv/bin/activate # On Windows, use venv\Scripts\activate

Install the WebSocket library #

pip install websockets server.py:import asyncio import websockets import json

A set to store all connected client websockets #

CONNECTED_CLIENTS = set()

async def handler(websocket): """ Handles a new client connection and listens for messages. """ # Add the new client to our set CONNECTED_CLIENTS.add(websocket) print(f"New client connected. Total clients: {len(CONNECTED_CLIENTS)}")

try:
    # Listen for incoming messages indefinitely
    async for message in websocket:
        print(f"Received message: {message}")
        # Broadcast the message to all clients
        tasks = [client.send(message) for client in CONNECTED_CLIENTS]
        await asyncio.gather(*tasks)
finally:
    # Remove the client when they disconnect
    CONNECTED_CLIENTS.remove(websocket)
    print(f"Client disconnected. Total clients: {len(CONNECTED_CLIENTS)}")

async def main(): """ Starts the WebSocket server. """ async with websockets.serve(handler, "localhost", 8765): print("Server is running on ws://localhost:8765") await asyncio.Future() # Run forever

if name == "main": asyncio.run(main()) Run the server:python server.py Other Popular FrameworksThe broadcasting logic is simple to replicate in other languages and frameworks:Go: Use the gorilla/websocket package. Maintain a map or slice of connected clients and iterate over it to send messages.Rust: Use a crate like tungstenite. Use channels and a shared state (like an Arc<Mutex<...>>) to manage connections.Socket.IO (Node.js): Simplifies broadcasting with io.emit('chat message', msg);.Django Channels (Python): Provides a high-level abstraction for WebSockets within the Django framework, managing connections in "groups".ContributingContributions are welcome! If you find a bug or have a feature request, please open an issue on our GitHub repository.LicenseThis package is licensed under the MIT License. See the LICENSE file for details.

11
likes
0
points
33
downloads

Publisher

unverified uploader

Weekly Downloads

A highly customizable and easy-to-use chat UI package for Flutter. It provides a complete chat screen designed to be powered by a real-time backend like WebSockets.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter

More

Packages that depend on swift_chat