FLUTTER • IN-APP CHAT • STEP-BY-STEP

How to add in-app chat to a Flutter app

Build real-time, room-based chat in Flutter with the RTCExpress chat SDK plugin from pub.dev. You will have two devices sending messages to each other instantly, with message history loaded when the screen opens, and no chat server, database or WebSocket code to write yourself.

Works on the Free planFree projects include in-app chat with a one-time trial of 10,000 messages, so you can follow this tutorial without a paid plan. Create a free project to get an App ID. See pricing for paid limits.

1. What you need

  • Flutter 3.19 or newer (flutter --version).
  • Two Android devices, or one Android phone and an Android emulator, on Android 7.0 (API 24) or newer.
  • A free RTCExpress project. Its App ID is in the customer console.

Android is the supported platform for the Flutter plugin today; iOS is experimental and not yet verified on devices. Loading history with getHistory is Android-only; on iOS, read history from the REST API instead.

2. Create an app and install the plugin

Create a new Flutter project and add the rtcexpress plugin:

flutter create chat_demo
cd chat_demo
flutter pub add rtcexpress

Open android/app/build.gradle.kts (or build.gradle) and make sure the minimum SDK is at least 24:

defaultConfig {
    minSdk = 24
    // ...keep the other generated values
}

Chat needs no runtime permissions. The plugin already declares internet access.

3. Write the chat screen

Replace lib/main.dart with this. It is the whole app: it connects, joins a room, loads recent messages, and sends and receives new ones.

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

// Test values from the console's Token tools, passed with --dart-define.
// In a real app, fetch the token from your own backend. Never ship an App Secret.
const appId = String.fromEnvironment('RTC_APP_ID');
const userId = String.fromEnvironment('RTC_USER_ID');
const token = String.fromEnvironment('RTC_TOKEN');
const roomId = 'chat-test';

void main() => runApp(const MaterialApp(home: ChatScreen()));

class ChatMessage {
  const ChatMessage(this.from, this.text);
  final String from;
  final String text;
}

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

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final rtc = RTCExpress();
  final input = TextEditingController();
  final messages = <ChatMessage>[];
  String status = 'Connecting...';
  bool joined = false;

  @override
  void initState() {
    super.initState();
    rtc.on('roomJoined', (_) {
      setState(() {
        joined = true;
        status = 'Joined $roomId';
      });
      loadHistory();
    });
    // Messages from the other people in the room.
    rtc.on('message', (p) => setState(() {
          messages.add(ChatMessage(p['fromUserId'] as String, p['text'] as String));
        }));
    rtc.on('error', (p) => setState(() => status = 'Error: ${p['message']}'));
    connect();
  }

  Future<void> connect() async {
    try {
      await rtc.init(const RTCInitOptions(
        serverUrl: 'https://api.devsquarelabs.com',
        appId: appId,
        userId: userId,
        token: token,
      ));
      await rtc.joinRoom(roomId);
    } catch (e) {
      setState(() => status = 'Error: $e');
    }
  }

  // Loads the last 50 messages. Call it after roomJoined: history is for room members only.
  Future<void> loadHistory() async {
    try {
      final page = await rtc.getHistory(roomId);
      final stored = (page['messages'] as List? ?? const [])
          .map((m) => ChatMessage(m['fromUserId'] as String, m['text'] as String))
          .toList()
          .reversed; // the server returns the newest first
      setState(() => messages.insertAll(0, stored));
    } catch (e) {
      setState(() => status = 'Could not load history: $e');
    }
  }

  Future<void> send() async {
    final text = input.text.trim();
    if (text.isEmpty) return;
    input.clear();
    await rtc.sendMessage(text);
    // The server sends your message to everyone else in the room, so add it here yourself.
    setState(() => messages.add(ChatMessage(userId, text)));
  }

  @override
  void dispose() {
    rtc.destroy();
    input.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Chat: $userId')),
      body: SafeArea(
        child: Column(
          children: [
            Padding(padding: const EdgeInsets.all(8), child: Text(status)),
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.all(12),
                itemCount: messages.length,
                itemBuilder: (context, i) {
                  final m = messages[i];
                  final mine = m.from == userId;
                  return Align(
                    alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
                    child: Container(
                      margin: const EdgeInsets.symmetric(vertical: 4),
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                        color: mine ? Colors.teal.shade100 : Colors.grey.shade200,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(mine ? m.text : '${m.from}: ${m.text}'),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: input,
                      enabled: joined,
                      decoration: const InputDecoration(hintText: 'Type a message'),
                      onSubmitted: (_) => send(),
                    ),
                  ),
                  IconButton(icon: const Icon(Icons.send), onPressed: joined ? send : null),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

How it works

  • init connects to RTCExpress with a short-lived user token, and joinRoom asks to join the room. The roomJoined event confirms membership, and only then can the user send or read history.
  • sendMessage sends text to the current room. The server stores it and delivers it to everyone else in the room, so the app adds your own message to the list itself.
  • The message event fires for each new message from someone else, with fromUserId, text and sentAt.
  • getHistory returns the latest messages, newest first, plus a nextCursor. Pass that cursor as before to load older pages: rtc.getHistory(roomId, before: cursor).
  • destroy runs in dispose and closes the connection.

4. Create two test tokens

Log in to your customer console → Token tools and create two short-lived tokens in the same project and room:

  • User ID alice, room ID chat-test.
  • User ID bob, room ID chat-test.
Use user tokens, never your App SecretTest tokens expire, which is what you want. Your App Secret must never be built into a mobile app, because anyone can extract it from the APK.

5. Run it on two devices

List your devices with flutter devices. Start the app on the first one as Alice:

flutter run -d FIRST_DEVICE_ID --dart-define=RTC_APP_ID=YOUR_APP_ID --dart-define=RTC_USER_ID=alice --dart-define=RTC_TOKEN=ALICE_TOKEN

In a second terminal, start it on the other device as Bob:

flutter run -d SECOND_DEVICE_ID --dart-define=RTC_APP_ID=YOUR_APP_ID --dart-define=RTC_USER_ID=bob --dart-define=RTC_TOKEN=BOB_TOKEN
  1. Wait until both screens show Joined chat-test.
  2. Type a message on Alice's device and press send. It appears on Bob's device straight away.
  3. Reply from Bob, then close and reopen the app on one device: the earlier messages load from history.

Troubleshooting

  • Send button stays disabled: the app hasn't joined the room. Check the App ID and that the token is for room chat-test and hasn't expired.
  • Messages don't arrive on the other device: both users must be in the same room, and the other app must be open and connected.
  • "Could not load history: Join the room first": history is read only after roomJoined, as in the code above.
  • Build fails with a minSdk error: set minSdk = 24, then run flutter clean.
  • Error that the message limit is reached: the project used its included messages. See pricing.

6. Before you ship

Replace the --dart-define token with a call to your own backend. Your server signs the user in, checks they may join the room (for example, a one-to-one chat between two users), and requests a short-lived token from POST https://api.devsquarelabs.com/v1/token with your App ID and App Secret; the Node.js server SDK or Python server SDK does this in a few lines. The App Secret stays on the server.

Then add the parts every chat needs: a stable room ID per conversation (for example dm_alice__bob), loading older pages with nextCursor, a "sending…" state while offline, and push notifications for messages that arrive while the app is closed (see the push notification setup guide).

Flutter chat questions

Do I need my own chat server or database?

No. RTCExpress hosts the real-time connection and stores message history. Your backend only issues tokens.

Can users call each other from the chat?

Yes. The same plugin makes voice and video calls in the same room: rtc.callUser('bob'). Follow the Flutter voice calling tutorial to add a call button.

How are messages counted?

Each message sent counts once, however many people are in the room. The Free trial includes 10,000 messages in total, Starter 100,000 a month and Pro 500,000 a month. See pricing.

Is there a web version?

Yes. The JavaScript in-app chat tutorial uses the same project, rooms and history, so web and mobile users can chat in one room.