chat_message_core
Pure Dart data models and core logic for chat messaging. No Flutter dependency — use in server-side Dart, background isolates, CLI tools, or as the foundation for a Flutter chat UI.
This package is the data layer companion to chat_message_ui_kit, which re-exports all types defined here.
Features
- Pure Dart — no Flutter, no
dart:ui; runs anywhere Dart runs - Message models —
TextMessageModel,ImageMessageModel,AudioMessageModel,VideoMessageModelwith a sharedMessageModelbase - User and room models —
ChatUser,Room - Partial message models — build messages incrementally before all data is available
- Link preview — fetch Open Graph / Twitter Card metadata from URLs via
getPreviewData() - Chat message processor —
calculateChatMessages()inserts date headers, spacers, and unread markers - Localization —
ChatL10nwith 15 built-in language implementations - Value equality — all models extend
Equatable - JSON serialization — all models annotated with
@JsonSerializable - Immutable with
copyWith— all models are immutable and support partial updates
Installation
dependencies:
chat_message_core: ^0.0.1
import 'package:chat_message_core/chat_message_core.dart';
Quick Start
import 'package:chat_message_core/chat_message_core.dart';
void main() {
// Create a user
final user = ChatUser(
id: 'user-1',
firstName: 'Alice',
lastName: 'Smith',
);
// Create a text message
final message = TextMessageModel(
id: 'msg-1',
author: user,
createdAt: DateTime.now().millisecondsSinceEpoch,
text: 'Hello, world!',
status: Status.sent,
type: MessageType.text,
);
// Serialize to JSON
final json = message.toJson();
print(json);
// Deserialize from JSON
final restored = MessageModel.fromJson(json);
print(restored == message); // true
// Immutable update
final updated = message.copyWith(status: Status.seen);
print(updated.status); // Status.seen
}
API Reference
Enums
MessageType
enum MessageType { audio, image, text, video }
Status
Delivery and read status for messages.
enum Status { delivered, error, seen, sending, sent }
ParsedType
Used in text parsing to identify inline content types.
enum ParsedType { email, phone, url }
Core Models
MessageModel (abstract)
Base class for all message types. Use MessageModel.fromJson(json) to deserialize — it dispatches to the correct subclass based on the type field.
| Property | Type | Description |
|---|---|---|
id |
String |
Unique message identifier |
author |
ChatUser |
Message sender |
createdAt |
int |
Unix timestamp (milliseconds) |
type |
MessageType |
Determines the concrete subclass |
status |
Status? |
Delivery/read status |
remoteId |
String? |
ID on external system |
roomId |
String? |
Room this message belongs to |
repliedMessage |
MessageModel? |
Quoted/replied message |
showStatus |
bool? |
Whether to show status indicator |
updatedAt |
int? |
Last-updated timestamp |
TextMessageModel
Extends MessageModel. Additional properties:
| Property | Type | Description |
|---|---|---|
text |
String |
Message text content |
previewData |
PreviewData? |
Link preview metadata |
ImageMessageModel
| Property | Type | Description |
|---|---|---|
name |
String |
Filename |
uri |
String |
Image URL or local path |
size |
num |
File size in bytes |
width |
double? |
Image width in pixels |
height |
double? |
Image height in pixels |
AudioMessageModel
| Property | Type | Description |
|---|---|---|
name |
String |
Filename |
uri |
String |
Audio URL or local path |
size |
num |
File size in bytes |
duration |
Duration |
Audio duration |
mimeType |
String? |
MIME type |
VideoMessageModel
| Property | Type | Description |
|---|---|---|
name |
String |
Filename |
uri |
String |
Video URL or local path |
size |
num |
File size in bytes |
width |
double? |
Video width in pixels |
height |
double? |
Video height in pixels |
ChatUser
final user = ChatUser(
id: 'user-1', // required
firstName: 'Alice',
lastName: 'Smith',
imageUrl: 'https://example.com/avatar.jpg',
createdAt: DateTime.now(),
);
print(getUserName(user)); // "Alice Smith"
print(getUserInitials(user)); // "AS"
Room
final room = Room(
id: 'room-1', // required
users: [user1, user2], // required
name: 'General',
imageUrl: 'https://example.com/room.jpg',
lastMessages: [latestMessage],
);
Partial Models
Partial models are used to construct messages before all properties are known (e.g. before server assigns an ID).
// Build from a partial using a factory constructor
final partial = PartialTextModel(text: 'Hello!');
final message = TextMessageModel.fromPartial(
partial,
id: 'msg-1',
author: user,
createdAt: DateTime.now().millisecondsSinceEpoch,
status: Status.sending,
);
Available partial types: PartialTextModel, PartialImageModel, PartialAudioModel, PartialVideoModel.
Link Preview
// Fetch Open Graph / Twitter Card metadata from a URL
final previewData = await getPreviewData('https://flutter.dev');
print(previewData.title); // "Flutter - Build apps for any screen"
print(previewData.description); // "..."
print(previewData.image?.url); // "https://..."
// Attach preview to a message
final messageWithPreview = message.copyWith(previewData: previewData);
PreviewData properties: title, description, link, image (PreviewDataImage with url, width, height).
getPreviewData supports an optional proxy URL, custom user-agent, and request timeout.
UI Helper Models
These are inserted by calculateChatMessages() into the display list alongside message models.
| Type | Purpose |
|---|---|
DateHeader |
Date/time separator displayed between messages from different days |
MessageSpacer |
Vertical gap between message groups |
UnreadHeaderData |
Marker placed above the first unread message |
PreviewImage |
Image gallery entry (id, uri) |
Utilities
calculateChatMessages()
Transforms a flat message list into a complete chat display structure — inserting date headers, spacers, and unread markers — and extracts an image gallery.
final result = calculateChatMessages(
messages, // List<MessageModel>, newest first
currentUser,
dateHeaderThreshold: 900000, // ms between messages before inserting a date header
groupMessagesThreshold: 60000, // ms between messages before breaking a group
showUserNames: true,
isWeb: false,
);
final List<Object> chatItems = result[0]; // mix of MessageModel, DateHeader, MessageSpacer, UnreadHeaderData
final List<PreviewImage> gallery = result[1]; // all image messages as gallery entries
Optional parameters: dateFormat, timeFormat, dateLocale, customDateHeaderText, lastReadMessageId, dateIsUtc.
formatBytes(int bytes)
Converts a byte count to a human-readable string.
formatBytes(1024); // "1 kB"
formatBytes(1536); // "1.5 kB"
formatBytes(1073741824); // "1 GB"
getUserName(ChatUser) / getUserInitials(ChatUser)
getUserName(ChatUser(id: '1', firstName: 'Alice', lastName: 'Smith')); // "Alice Smith"
getUserInitials(ChatUser(id: '1', firstName: 'Alice', lastName: 'Smith')); // "AS"
Localization
Extend ChatL10n or use one of the 15 built-in implementations:
| Class | Language |
|---|---|
ChatL10nEn |
English (default) |
ChatL10nEs |
Spanish |
ChatL10nDe |
German |
ChatL10nAr |
Arabic |
ChatL10nFa |
Persian |
ChatL10nFi |
Finnish |
ChatL10nKo |
Korean |
ChatL10nPl |
Polish |
ChatL10nPt |
Portuguese |
ChatL10nRu |
Russian |
ChatL10nSe |
Swedish |
ChatL10nTr |
Turkish |
ChatL10nUk |
Ukrainian |
ChatL10nZhCN |
Simplified Chinese |
ChatL10nZhTW |
Traditional Chinese |
Localizable strings: inputPlaceholder, sendButtonAccessibilityLabel, attachmentButtonAccessibilityLabel, fileButtonAccessibilityLabel, emptyChatPlaceholder, unreadMessagesLabel.
final l10n = ChatL10nEs(); // Spanish
print(l10n.inputPlaceholder); // "Mensaje"
Regex Exports
regexEmail // Email address pattern
regexLink // URL pattern
Code Generation
Models use json_serializable. After modifying any model, regenerate the .g.dart files:
dart run build_runner build --delete-conflicting-outputs
Relationship to chat_message_ui_kit
chat_message_ui_kit re-exports everything from chat_message_core. Flutter app consumers who import chat_message_ui_kit already have access to all types in this package — no pubspec.yaml changes required.
Use chat_message_core directly when you need these types without pulling in Flutter:
- Server-side Dart (shelf, dart_frog, etc.)
- Background isolates
- CLI tools and scripts
- Shared data layer in a multi-platform project
License
MIT