Group Chat
Loading preview
Starting the Flutter app
A showcase of a simple group chat UI in flutter
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';
class User {
final String id;
final String name;
final Color color;
User({required this.id, required this.name, required this.color});
}
class Message {
final String text;
final User sender;
final DateTime timestamp;
Message({required this.text, required this.sender, required this.timestamp});
}
class ChatService {
final StreamController<Message> _messageController =
StreamController<Message>.broadcast();
final StreamController<Set<User>> _typingController =
StreamController<Set<User>>.broadcast();
final Random _random = Random();
final Map<Timer, User> _pendingReplies = {};
// Simulated users
final List<User> users = [
User(id: '1', name: 'You', color: Colors.blue),
User(id: '2', name: 'Alice', color: Colors.purple),
User(id: '3', name: 'Bob', color: Colors.green),
User(id: '4', name: 'Charlie', color: Colors.orange),
];
User get currentUser => users[0];
Stream<Message> get messageStream => _messageController.stream;
Stream<Set<User>> get typingStream => _typingController.stream;
void sendMessage(String text) {
if (text.trim().isEmpty) return;
final message = Message(
text: text,
sender: currentUser,
timestamp: DateTime.now(),
);
_messageController.add(message);
_simulateResponses(text);
}
// Emits a copy, so listeners never hold a set that changes under them.
void _emitTyping() => _typingController.add(_pendingReplies.values.toSet());
void _simulateResponses(String originalMessage) {
// Random number of responses (1-3)
final numResponses = _random.nextInt(3) + 1;
for (var i = 0; i < numResponses; i++) {
// Random delay between 1-3 seconds
final delay = _random.nextInt(3) + 1;
// Pick a random user (excluding current user)
final randomUser = users[_random.nextInt(users.length - 1) + 1];
late final Timer timer;
timer = Timer(Duration(seconds: delay), () {
// A user stays typing until their last pending reply lands
_pendingReplies.remove(timer);
_emitTyping();
final response = Message(
text: "${randomUser.name} responds to: $originalMessage",
sender: randomUser,
timestamp: DateTime.now(),
);
_messageController.add(response);
});
_pendingReplies[timer] = randomUser;
}
// Show typing indicator
_emitTyping();
}
void dispose() {
for (final timer in _pendingReplies.keys) {
timer.cancel();
}
_pendingReplies.clear();
_messageController.close();
_typingController.close();
}
}
class GroupChat extends StatefulWidget {
const GroupChat({super.key});
@override
State<GroupChat> createState() => _GroupChatState();
}
class _GroupChatState extends State<GroupChat> {
final TextEditingController _controller = TextEditingController();
final ScrollController _scrollController = ScrollController();
final ChatService _chatService = ChatService();
final List<Message> _messages = [];
Set<User> _typingUsers = {};
late final StreamSubscription<Message> _messageSubscription;
late final StreamSubscription<Set<User>> _typingSubscription;
@override
void initState() {
super.initState();
_messageSubscription = _chatService.messageStream.listen((message) {
setState(() {
_messages.add(message);
});
_scrollToBottom();
});
_typingSubscription = _chatService.typingStream.listen((users) {
setState(() {
_typingUsers = users;
});
});
}
@override
void dispose() {
_messageSubscription.cancel();
_typingSubscription.cancel();
_controller.dispose();
_scrollController.dispose();
_chatService.dispose();
super.dispose();
}
void _sendMessage(String text) {
_chatService.sendMessage(text);
_controller.clear();
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
Widget _buildAvatar(User user) {
return CircleAvatar(
backgroundColor: user.color,
child: Text(
user.name[0].toUpperCase(),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
);
}
Widget _buildTypingIndicator(User user) {
return Padding(
padding: const EdgeInsets.only(left: 16, bottom: 8),
child: Row(
children: [
_buildAvatar(user),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[800]
: Colors.grey[200],
borderRadius: BorderRadius.circular(20),
),
child: const _TypingDots(),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Group Chat')),
body: Column(
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: _messages.length + _typingUsers.length,
itemBuilder: (context, index) {
if (index >= _messages.length) {
final typingUser = _typingUsers.elementAt(
index - _messages.length,
);
return _buildTypingIndicator(typingUser);
}
final message = _messages[index];
final isMe = message.sender.id == _chatService.currentUser.id;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
mainAxisAlignment: isMe
? MainAxisAlignment.end
: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isMe) ...[
_buildAvatar(message.sender),
const SizedBox(width: 8),
],
Flexible(
child: Column(
crossAxisAlignment: isMe
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
if (!isMe)
Padding(
padding: const EdgeInsets.only(
left: 8,
bottom: 4,
),
child: Text(
message.sender.name,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
decoration: BoxDecoration(
color: isMe
? Theme.of(context).primaryColor
: Theme.of(context).brightness ==
Brightness.dark
? Colors.grey[800]
: Colors.grey[200],
borderRadius: BorderRadius.circular(20),
),
child: Text(
message.text,
style: TextStyle(
color: isMe
? Colors.white
: Theme.of(context).brightness ==
Brightness.dark
? Colors.white
: Colors.black,
),
),
),
],
),
),
if (isMe) ...[
const SizedBox(width: 8),
_buildAvatar(message.sender),
],
],
),
);
},
),
),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Theme.of(context).scaffoldBackgroundColor
: Colors.white,
boxShadow: [
BoxShadow(
color: Theme.of(context).brightness == Brightness.dark
? Colors.black.withValues(alpha: 0.2)
: Colors.grey.withValues(alpha: 0.2),
spreadRadius: 1,
blurRadius: 3,
offset: const Offset(0, -1),
),
],
),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
style: TextStyle(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white
: Colors.black,
),
decoration: InputDecoration(
hintText: 'Type a message...',
hintStyle: TextStyle(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[400]
: Colors.grey[600],
),
border: InputBorder.none,
),
onSubmitted: _sendMessage,
),
),
IconButton(
tooltip: 'Send message',
icon: Icon(Icons.send, color: Theme.of(context).primaryColor),
onPressed: () => _sendMessage(_controller.text),
),
],
),
),
],
),
);
}
}
class _TypingDots extends StatefulWidget {
const _TypingDots();
@override
State<_TypingDots> createState() => _TypingDotsState();
}
class _TypingDotsState extends State<_TypingDots>
with SingleTickerProviderStateMixin {
late final AnimationController _bounce = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 900),
)..repeat();
@override
void dispose() {
_bounce.dispose();
super.dispose();
}
Widget _buildDot(int index, Color color) {
final start = index * 0.2;
final hop = Interval(start, start + 0.4, curve: Curves.easeInOut);
return Transform.translate(
offset: Offset(0, -4 * sin(pi * hop.transform(_bounce.value))),
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
),
);
}
@override
Widget build(BuildContext context) {
final color = Theme.of(context).brightness == Brightness.dark
? Colors.grey[400]!
: Colors.grey[600]!;
return AnimatedBuilder(
animation: _bounce,
builder: (context, _) => Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildDot(0, color),
const SizedBox(width: 4),
_buildDot(1, color),
const SizedBox(width: 4),
_buildDot(2, color),
],
),
);
}
}
Add it to your project
Copies the Dart source into your app, so you own it. Flutter SDK only, no extra packages.
First time? Run dart pub global activate fluttertemplates_dev, or read the CLI guide.
How it works
ChatService is a local simulation exposing broadcast streams for messages and typing. _simulateResponses picks one to three random users and echoes your text after 1 to 3 seconds. Each reply is a Timer in _pendingReplies, and typingStream emits the users still holding one, so overlapping replies stay correct. dispose cancels those timers before closing the controllers. _TypingDots loops on a repeating AnimationController.
Adapting it
- Replace
sendMessageand_simulateResponseswith your socket client, keepingmessageStreamandtypingStreamas the interface. - Render
timestamp, which is recorded but never displayed.