Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 73 ยท Projects

Project: Realtime Chat App

Build a Flutter chat app: a message stream from Firestore or a WebSocket, sign-in, a message list and optimistic sends with retry on failure.

A chat app is the best test of your understanding of streams. Messages arrive whenever someone else types, not when you ask. The list must update by itself, new messages must scroll into view, and your own messages should appear instantly, even before the server has confirmed them.

In this project you design the chat's data flow: sign-in, a message stream, the list UI and optimistic sends that handle failure. It builds on WebSockets and Realtime Data, Firebase: Auth, Firestore and Cloud Messaging and FutureBuilder, StreamBuilder and Async UI.

Real vs stand-in. The Dart and Firebase code is real and read-only, because the site cannot sign in to Firebase or open sockets from Dart. The live examples are JavaScript stand-ins: a fake backend that pushes messages, an async iterator that acts like a Stream, and an optimistic-send controller whose fake server sometimes fails.

What a chat needs

Identity Know who is sending.
Live stream Messages arrive by themselves.
Message list Newest at the bottom.
Instant feel Show your message at once.
1 / 2

Step 1: the model and the backend contract

Start with the data and a small interface. The UI will talk to the interface, so you can use Firestore today and a WebSocket server tomorrow:

DART
enum SendStatus { sending, sent, failed }

class Message {
  const Message({
    required this.id,
    required this.senderId,
    required this.senderName,
    required this.text,
    required this.sentAt,
    this.status = SendStatus.sent,
  });

  final String id;
  final String senderId;
  final String senderName;
  final String text;
  final DateTime sentAt;
  final SendStatus status;

  Message copyWith({SendStatus? status}) => Message(
        id: id, senderId: senderId, senderName: senderName,
        text: text, sentAt: sentAt, status: status ?? this.status,
      );
}

abstract class ChatBackend {
  Stream<List<Message>> watchMessages(String roomId);
  Future<void> send(String roomId, Message message);
}

Step 2: authentication

Everything depends on knowing the user, so gate the chat behind sign-in. With Firebase Authentication, the current user is itself a stream:

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Scaffold(body: Center(child: CircularProgressIndicator()));
        }
        final user = snapshot.data;
        return user == null ? const SignInScreen() : ChatScreen(user: user);
      },
    );
  }
}

Signing in or out changes the stream, and the gate swaps screens by itself: no manual navigation. Sign-in forms follow Forms and Validation. A chat also needs server-side rules: the client must never be trusted to say who the sender is (see the security rules in the Firebase lesson).

Step 3: the Firestore backend

Messages live in a subcollection rooms/{roomId}/messages. snapshots() is a stream that emits again whenever data changes:

DART
class FirestoreBackend implements ChatBackend {
  final _db = FirebaseFirestore.instance;

  @override
  Stream<List<Message>> watchMessages(String roomId) {
    return _db
        .collection('rooms/$roomId/messages')
        .orderBy('sentAt', descending: true)
        .limit(50)
        .snapshots()
        .map((snap) => [
              for (final doc in snap.docs)
                Message(
                  id: doc.id,
                  senderId: doc['senderId'] as String,
                  senderName: doc['senderName'] as String,
                  text: doc['text'] as String,
                  sentAt: (doc['sentAt'] as Timestamp?)?.toDate() ?? DateTime.now(),
                ),
            ]);
  }

  @override
  Future<void> send(String roomId, Message message) {
    return _db.collection('rooms/$roomId/messages').doc(message.id).set({
      'senderId': message.senderId,
      'senderName': message.senderName,
      'text': message.text,
      'sentAt': FieldValue.serverTimestamp(),
    });
  }
}

Two details matter. The query asks for the newest 50 (descending with a limit) so the chat does not download the whole history; the UI shows them with ListView(reverse: true), which keeps the newest at the bottom and needs no manual scrolling. And the client picks the message id itself, so the same message can be matched when the server echoes it back.

If you use a WebSocket server instead, implement the same interface with web_socket_channel, as in the realtime lesson.

Step 4: the optimistic controller

Waiting for the server before showing your own message makes the app feel slow. Optimistic sending adds the message to the list immediately as sending, then marks it sent or failed. When the stream later delivers the real copy with the same id, the real one replaces the temporary one:

DART
class ChatController extends ChangeNotifier {
  ChatController(this._backend, this._roomId, this._me) {
    _subscription = _backend.watchMessages(_roomId).listen((serverMessages) {
      _server = serverMessages;
      notifyListeners();
    });
  }

  final ChatBackend _backend;
  final String _roomId;
  final User _me;
  late final StreamSubscription<List<Message>> _subscription;

  List<Message> _server = [];                    // newest first
  final Map<String, Message> _pending = {};      // by id

  List<Message> get messages {
    final serverIds = {for (final m in _server) m.id};
    final stillPending = _pending.values.where((m) => !serverIds.contains(m.id));
    return [...stillPending.toList().reversed, ..._server];
  }

  Future<void> send(String text) async {
    final clean = text.trim();
    if (clean.isEmpty) return;
    final message = Message(
      id: const Uuid().v4(),
      senderId: _me.uid,
      senderName: _me.displayName ?? 'Me',
      text: clean,
      sentAt: DateTime.now(),
      status: SendStatus.sending,
    );
    _pending[message.id] = message;
    notifyListeners();
    await _deliver(message);
  }

  Future<void> retry(String id) async {
    final message = _pending[id];
    if (message == null) return;
    _pending[id] = message.copyWith(status: SendStatus.sending);
    notifyListeners();
    await _deliver(_pending[id]!);
  }

  Future<void> _deliver(Message message) async {
    try {
      await _backend.send(_roomId, message);
      _pending.remove(message.id);               // the stream now owns it
    } catch (_) {
      _pending[message.id] = message.copyWith(status: SendStatus.failed);
    }
    notifyListeners();
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }
}

Using one id for the pending and the real message is the key: without it, the user would briefly see the message twice. Firestore also keeps writes in an offline queue, but the pattern above works with any backend and gives you control over the failed state.

Step 5: the message list

DART
ListView.builder(
  reverse: true,                                  // index 0 is the newest, at the bottom
  itemCount: controller.messages.length,
  itemBuilder: (context, index) {
    final message = controller.messages[index];
    final mine = message.senderId == me.uid;
    return Align(
      alignment: mine ? Alignment.centerRight : Alignment.centerLeft,
      child: GestureDetector(
        onTap: message.status == SendStatus.failed ? () => controller.retry(message.id) : null,
        child: Opacity(
          opacity: message.status == SendStatus.sending ? 0.5 : 1,
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: mine ? Colors.indigo.shade100 : Colors.grey.shade200,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              message.status == SendStatus.failed ? '${message.text}  (tap to retry)' : message.text,
            ),
          ),
        ),
      ),
    );
  },
)

Stand-in: a message stream

A fake backend keeps messages and pushes the full list to subscribers, like snapshots(). An async iterator is the stand-in for the Stream.

JS A fake backend that pushes message lists

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: optimistic sends with failure and retry

The fake server rejects the first attempt of any message containing "fail". We print the status each time it changes.

JS Sending, sent, failed and retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ideas to extend it

  • Typing indicators and read receipts using a small presence document.
  • Pagination: load older messages when the user scrolls to the top.
  • Push notifications for new messages (see Camera, Location, Permissions and Notifications).
  • Image messages with upload progress.
  • A widget test that feeds a fake ChatBackend and checks the greyed-out state.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an optimistic send?

    The UI assumes success, then marks the message sent or failed once the result is known.
  2. 2. Why does the client create the message id itself?

    Using one id lets the stream's real copy replace the temporary pending one.
  3. 3. How does AuthGate switch between the sign-in and chat screens?

    The auth state is a stream, so the builder re-runs whenever the user signs in or out.
  4. 4. What does ListView(reverse: true) help with in a chat?

    With reverse, index 0 sits at the bottom, so feeding it newest-first data keeps new messages in view.

Summary

  • Hide the backend behind an interface so Firestore or WebSockets can be swapped.
  • Gate the chat with an auth stream; trust only server-side rules for identity.
  • Load a limited window of newest messages and show them with a reversed list.
  • Optimistic sends use sending, sent and failed states with one stable id and a retry path.
  • Cancel the stream subscription in dispose.

Next: Project: Shopping App with Cart and Navigation