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
ChatCoreFunctions().getPreviewData() - Chat message processor —
ChatCoreFunctions().calculateChatMessages()inserts date headers, spacers, and unread markers - Value equality — all models extend
Equatable - JSON serialization — all models annotated with
@JsonSerializable;toJson()produces plain nested maps - Immutable with
copyWith— all models are immutable and support partial updates, including setting nullable fields back tonull
Installation
dependencies:
chat_message_core: ^0.0.4
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
const user = ChatUser(
id: 'user-1',
firstName: 'Alice',
lastName: 'Smith',
);
// Create a text message (type defaults to MessageType.text)
final message = TextMessageModel(
id: 'msg-1',
author: user,
createdAt: DateTime.now().millisecondsSinceEpoch,
text: 'Hello, world!',
status: Status.sent,
);
// Serialize to JSON (nested values are plain maps)
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
// Explicitly clear a nullable field
final cleared = message.copyWith(status: null);
print(cleared.status); // null
}
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 and throws a StateError for an unknown type.
| 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 (milliseconds) |
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 (serialized as microseconds) |
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().millisecondsSinceEpoch,
);
final functions = ChatCoreFunctions();
print(functions.getUserName(user)); // "Alice Smith"
print(functions.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],
);
Two rooms are equal only if all fields match, including lastMessages, which is compared deeply. Because == and hashCode walk every last message and change when a new one arrives, key maps and sets by room.id, not by Room.
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
const partial = PartialTextModel(text: 'Hello!');
final message = TextMessageModel.fromPartial(
partialText: partial,
id: 'msg-1',
author: user,
createdAt: DateTime.now().millisecondsSinceEpoch,
status: Status.sending,
);
Available partial types: PartialTextModel, PartialImageModel, PartialAudioModel, PartialVideoModel. The matching factories take partialText:, partialImage:, partialAudio: and partialVideo:.
Link Preview
// Fetch Open Graph / Twitter Card metadata for the first link in a text
final previewData = await ChatCoreFunctions().getPreviewData(
'Check out 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).
Optional parameters:
| Parameter | Default | Description |
|---|---|---|
imageSizeResolver |
null |
Future<({double height, double width})> Function(String url) used to measure images. Without it, image dimensions are 0.0 and the first image is used. |
onError |
null |
void Function(Object error, StackTrace stackTrace) called when the request or parsing fails |
proxy |
null |
Prefix added to the request URL and to image URLs (for example a CORS proxy on web). link always holds the original URL. |
requestTimeout |
5 seconds | Timeout for the whole request, headers and body |
userAgent |
WhatsApp/2 |
User-Agent header |
Behavior:
- Text with no link returns an empty
PreviewDatawithout making a request. getPreviewDatadoes not throw. If the request fails, times out or returns a non-2xx status, it returns aPreviewDatawith whatever it found so far (usually justlink) and passes the error toonError. In debug builds the error is also logged withdart:developer.- A direct image link (
image/*) returns an image preview without downloading the image body. SVG and GIF links return onlylink, the same way SVG and GIFog:imageand<img>tags are skipped. - Other non-HTML responses (PDF, video, ...) return only
link. - HTML is decoded with the charset from the
Content-Typeheader or a<meta>tag (UTF-8, Latin-1 or ASCII), defaulting to UTF-8. Pages in other charsets return onlylink.
UI Helper Models
These are inserted by calculateChatMessages() into the display list.
| Type | Purpose |
|---|---|
DateHeader |
Date/time separator displayed between messages from different days or far apart in time |
MessageSpacer |
Vertical gap between message groups |
UnreadHeaderData |
Marker placed above the first unread message |
PreviewImage |
Image gallery entry (id, uri) |
Utilities
All utility functions are instance methods on ChatCoreFunctions. Regex patterns are static members of ChatCoreRegex.
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 = ChatCoreFunctions().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 chatItems = result[0] as List<Object>; // newest first
final gallery = result[1] as List<PreviewImage>; // oldest first
chatItems mixes DateHeader, MessageSpacer, UnreadHeaderData and one map per message:
{
'message': MessageModel,
'nextMessageInGroup': bool, // the next message continues this group
'showName': bool, // show the author's name above this message
'showStatus': bool, // message.showStatus ?? true
}
Optional parameters: dateFormat, timeFormat, dateLocale, customDateHeaderText, lastReadMessageId, dateIsUtc. With isWeb: true, only images with http or blob URIs are added to the gallery.
formatBytes(int bytes, [int fractionDigits = 2])
Converts a byte count to a human-readable string (1024-based).
final functions = ChatCoreFunctions();
functions.formatBytes(1024); // "1.00 kB"
functions.formatBytes(1536, 1); // "1.5 kB"
functions.formatBytes(1073741824); // "1.00 GB"
getUserName(ChatUser) / getUserInitials(ChatUser)
final functions = ChatCoreFunctions();
functions.getUserName(const ChatUser(id: '1', firstName: 'Alice', lastName: 'Smith')); // "Alice Smith"
functions.getUserInitials(const ChatUser(id: '1', firstName: 'Alice', lastName: 'Smith')); // "AS"
formattedDateTimeRep(DateTime)
Formats a date header label: only the time for today ("14:05"), otherwise date and time ("Mar 15, 14:05"). Accepts dateFormat, timeFormat and dateLocale.
Regex
ChatCoreRegex.regexEmail // String pattern: email address
ChatCoreRegex.regexLink // String pattern: URL, with or without scheme
ChatCoreRegex.regexImageContentType // String pattern: image/* content types
ChatCoreRegex.urlRegex // RegExp: text before + URL starting with http(s):// or www.
ChatCoreRegex.looseUrlRegex // RegExp: like urlRegex, also matches bare domains
ChatCoreRegex.protocolIdentifierRegex // RegExp: leading http:// or https://
Development
Models use json_serializable (configured in build.yaml with explicit_to_json: true). After modifying any model, regenerate the .g.dart files:
dart run build_runner build --delete-conflicting-outputs
Run the tests:
dart test
Tests never touch the network. Link preview tests use MockClient from package:http/testing.dart.
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