How We Fixed a 37-Second System ANR in Flutter RichText (Justify + Syllable Hyphenation + Bionic Reading)
Unit tests are dangerously polite. They pass a 200-character Lorem Ipsum paragraph into a Flutter widget tree, assert findsOneWidget, and turn green in 40 milliseconds. Real books are not 200 characters long.
While preparing v1.2.5 of Lector (app.lectorreader.audiobook), an offline Android EPUB/PDF audiobook reader written in Flutter, we ran a physical Hardware-in-the-Loop (HIL) test on a $180 Redmi Note 13 (Snapdragon 685, Android 14) opening a 40,000+-character chapter of The Adventures of Sherlock Holmes with three popular typography toggles turned on at the same time:
- Full justification (
TextAlign.justify) - Automatic visible syllable hyphenation (
-) - Bold Word Starts (bionic reading)
The screen froze completely. 37.3 seconds later, Android killed the UI with a hard System ANR. Here is why it happened, why naive fixes failed, and the exact frame-budgeted controller that cut cold open time from 37.3s ANR down to 3.86s (and 1.31s chapter switches) on the exact same phone.
Why TextAlign.justify + Hyphenation + Bold Spans Explodes in Flutter
Flutter's TextPainter does not automatically insert visible syllable hyphens (-) when breaking lines inside justified text. To achieve true print-book justification without ugly "rivers of whitespace" across narrow phone screens, you have to measure line wraps and place visible hyphens at valid syllable boundaries.
When you combine that with Bold Word Starts, every single word splits into two TextSpan children (boldPrefix + regularSuffix). A 40,000-character chapter quickly balloons into 14,000+ nested TextSpan nodes.
If you eagerly compute hyphenation and rebuild rich TextSpan trees for the entire chapter inside initState() or the first build() pass:
- Every paragraph runs repeated
TextPainter.layout(maxWidth: viewportWidth)passes on the UI isolate. - Measuring hundreds of long paragraphs synchronously blocks the Flutter raster/UI thread for tens of seconds.
- On a flagship Snapdragon 8 Gen 3, it feels like a sluggish 4-second stutter. On a budget Snapdragon 685, Android throws a fatal Application Not Responding (ANR) dialog.
Why Isolate.run Alone Cannot Fix TextPainter
Our first thought was: "Move hyphenation calculation into Isolate.run!" Two hard realities immediately broke that plan:
TextPaintercalls directly intodart:ui/ Skia / Impeller paragraph shaping, which cannot execute inside a background Dart isolate.- Even if you pre-calculate syllable candidate indices in an isolate (which we already do!), the final width measurement that decides which soft hyphen actually falls at the end of a rendered line depends on exact font metrics, font size, letter spacing, and
maxWidthon the main isolate.
The Fix: IncrementalVisibleHyphenController (Strict Frame Budgets)
Instead of trying to finish 300 paragraphs before Frame 0, we split typography layout into a two-speed state machine that respects Flutter's 16 ms frame budget:
- Viewport-First Frame 0 (12 ms budget):
- Immediately identify the paragraph range currently visible around the saved reading offset (or top of chapter).
- Run exact visible-hyphen shaping only for those visible paragraphs within a hard 12 ms stopwatch slice.
- Render the chapter immediately so the reader sees crisp justified text with visible hyphens on the very first painted screen.
- Incremental Background Slices (6 ms per frame):
- Schedule remaining off-screen paragraphs via
SchedulerBinding.instance.scheduleFrameCallbackin tiny 6 ms time slices. - Each completed paragraph notifies only its own
ValueNotifier/ item builder insideListView.builder(no full-chaptersetState()!). - If the user jumps via Table of Contents, search, or fast-scrolls, the priority cursor immediately retargets the new visible window first.
- Schedule remaining off-screen paragraphs via
- Fast Pagination Layout for Paged Mode:
- For E-ink and page-turning readers (
Paged Mode), we introduced a lightweight fast pagination layout path (buildFastPaginationLayout) so turning pages or switching themes never triggers full-chapter re-shaping stalls.
- For E-ink and page-turning readers (
Measured Before vs. After (Redmi Note 13, Snapdragon 685)
Tested on the exact same 40,000+-character chapter with Justify = ON + Bold Word Starts = ON + Visible Hyphens = ON:
| Metric | Before (Eager Pre-Pass) | After (IncrementalVisibleHyphenController) |
|---|---|---|
| Cold Book Open | 37.3s System ANR | 3.86s (0 ANR) |
| Chapter Switch | Freeze / ANR risk | 1.31s |
| 120 FPS Word Highlighting | Blocked / stalled | Smooth, 0 dropped frames |
Takeaway: Test Typography at Real-Book Scale
If you build any Flutter reader, note app, or rich-text viewer, add a real-scale stress test to your CI suite: feed your layout engine at least 40,000 characters of real prose with your heaviest typography toggles enabled simultaneously, and profile it on a mid-range $150-$200 Android device rather than a desktop simulator.
- Full Hardware Benchmark Notes (GitHub): https://github.com/fromych1/lector-app/blob/main/docs/BENCHMARKS.md
- Lector Website: https://lector.page
- Google Play Store: https://play.google.com/store/apps/details?id=app.lectorreader.audiobook
Comments
No comments yet. Start the discussion.