-
Notifications
You must be signed in to change notification settings - Fork 175
Description
assing to me please, I will send a PR
This addresses a critical bug that caused two distinct errors in the chat interface, primarily when rendering streaming markdown content with complex elements like code blocks.
-
The
!debugNeedsLayout
Error
Problem: When receiving a streaming response from the LLM, especially one containing markdown with code blocks, the application would frequently crash with a!debugNeedsLayout
assertion error. This indicated that a widget was being painted or processed while its layout was still being calculated, a common issue with frequent and inefficient state updates on complex widgets.
Root Cause: TheMarkit widget
, which renders markdown, was a StatelessWidget that rebuilt the entireMarkdownBlock
on every single data chunk received from the stream. This caused significant performance bottlenecks and race conditions in Flutter's rendering pipeline. -
Optimized Widget Reconciliation and State Management:
Unique Keys: Added unique ValueKeys toMessageBubble
widgets withinChatMessageContent
. This ensures Flutter's reconciliation algorithm can correctly identify and update widgets during rebuilds, preventing unnecessary tree mutations.
Lifecycle-Aware Caching inMarkit Widget
:
The _MarkitState was refactored to remove all context-dependent logic from initState.
The markdown rendering logic now resides entirely within the build method.
The rendered MarkdownBlock widget is cached in a state variable (_cachedMarkdown).
This cache is only invalidated and rebuilt if:
The input data string changes.
The Theme.of(context).brightness changes (to support dark/light mode switching).
This approach ensures that expensive markdown parsing and rendering only occur when absolutely necessary, respecting the widget lifecycle and eliminating both the layout and dependency errors.
These changes have made the chat interface more robust, performance, and free of rendering-related crashes, especially during real-time message streaming.