Flyweight Dart Example: Share Memory, Not Copies
10,000 list items, 50 distinct styles — so why hold 10,000 copies? This flyweight Dart example shows how to share immutable state through a factory cache and slash model memory in Flutter list views.
What if 10,000 list items cost the memory of 50? Picture a chat screen: 10,000 messages, but only 50 distinct authors. In the naive model, every message carries a full copy of its author — name, avatar URL, color, role. That's the same 50 authors stored 10,000 times. This flyweight dart example shows the fix: split each object into *intrinsic* state (shared, immutable — the author) and *extrinsic* state (unique per use — the message body and timestamp), pool one canonical author per user in a factory cache, and let every message point at the pool. 10,000 copies collapse into 50 shared instances, and the pattern generalizes to any list view where thousands of models repeat the same data. What You'll Build In this guide you will: Split a chat-list model into intrinsic (shared) and extrinsic (per-message) state Build a flyweight factory with a putIfAbsent cache — one canonical instance per key See how Dart's const constructors already share instances behind your back Wire the pattern into a ListView.builder the idiomatic Flutter way Learn to measure the win with DevTools memory snapshots Get a decision table: flyweight vs const vs plain cache vs singleton Learn the four mistakes that corrupt shared state (including the big one: mutation) All code targets Dart 3.13 and Flutter 3.47 (stable versions verified October 2026). Counting the Copies — the Memory Problem The naive chat model duplicates the author on every message: class ChatMessageNaive { final String id; final String body; final DateTime sentAt; // Duplicated on EVERY message, even for the same author: final String authorName; final String avatarUrl; final String colorHex; final String role; const ChatMessageNaive({ required this.id, required this.body, required this.sentAt, required this.authorName,…