cometchat_sdk 5.0.6 copy "cometchat_sdk: ^5.0.6" to clipboard
cometchat_sdk: ^5.0.6 copied to clipboard

CometChat enables you to add voice, video & text chat for your website & app. This guide demonstrates how to add chat to an Flutter application using CometChat.

example/lib/main.dart

// A minimal CometChat Flutter example.
//
// It shows the three calls every chat app starts with:
//   1. CometChat.init      – set up the SDK once at app start.
//   2. CometChat.login     – authenticate a user.
//   3. CometChat.sendMessage – send a text message to another user.
//
// Replace the placeholder credentials below with values from your CometChat
// dashboard (https://app.cometchat.com). Never ship a real Auth Key in a
// production client; use Auth Tokens generated from your server instead.

import 'package:cometchat_sdk/cometchat_sdk.dart';
import 'package:flutter/material.dart';

// TODO: Replace these with your own credentials from the CometChat dashboard.
const String appId = 'YOUR_APP_ID';
const String region = 'YOUR_REGION'; // e.g. 'us' or 'eu'
const String authKey = 'YOUR_AUTH_KEY';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'CometChat SDK Example',
      home: const HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _status = 'Not initialized';

  @override
  void initState() {
    super.initState();
    _initCometChat();
  }

  // Step 1: Initialize the SDK once, as early as possible in the app lifecycle.
  Future<void> _initCometChat() async {
    final appSettings = AppSettingsBuilder()
        .subscribePresenceForAllUsers()
        .setRegion(region)
        .build();

    await CometChat.init(
      appId,
      appSettings,
      onSuccess: (String message) {
        setState(() => _status = 'Initialized');
      },
      onError: (CometChatException e) {
        setState(() => _status = 'Init failed: ${e.message}');
      },
    );
  }

  // Step 2: Log a user in. For production, prefer loginWithAuthToken().
  Future<void> _login(String uid) async {
    setState(() => _status = 'Logging in...');
    // ignore: deprecated_member_use
    await CometChat.login(
      uid,
      authKey,
      onSuccess: (User user) {
        setState(() => _status = 'Logged in as ${user.name}');
      },
      onError: (CometChatException e) {
        setState(() => _status = 'Login failed: ${e.message}');
      },
    );
  }

  // Step 3: Send a text message to another user.
  Future<void> _sendMessage(String receiverUid, String text) async {
    final message = TextMessage(
      text: text,
      receiverUid: receiverUid,
      type: CometChatMessageType.text,
      receiverType: CometChatReceiverType.user,
    );

    await CometChat.sendMessage(
      message,
      onSuccess: (TextMessage sent) {
        setState(() => _status = 'Sent: ${sent.text}');
      },
      onError: (CometChatException e) {
        setState(() => _status = 'Send failed: ${e.message}');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('CometChat SDK Example')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(_status, textAlign: TextAlign.center),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: () => _login('superhero1'),
                child: const Text('Log in as superhero1'),
              ),
              const SizedBox(height: 12),
              ElevatedButton(
                onPressed: () =>
                    _sendMessage('superhero2', 'Hello from Flutter!'),
                child: const Text('Send message to superhero2'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
11
likes
160
points
2.81k
downloads

Documentation

API reference

Publisher

verified publishercometchat.com

Weekly Downloads

CometChat enables you to add voice, video & text chat for your website & app. This guide demonstrates how to add chat to an Flutter application using CometChat.

Homepage

License

MIT (license)

Dependencies

crypto, dio, flutter, flutter_secure_storage, idb_shim, json_annotation, path, shared_preferences, sqflite, sqflite_common_ffi, web_socket_channel

More

Packages that depend on cometchat_sdk