Skip to content

Rendering and Life-cycle Errors in Chat Message Streaming #140

@cevheri

Description

@cevheri

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.

  1. 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: The Markit widget, which renders markdown, was a StatelessWidget that rebuilt the entire MarkdownBlock on every single data chunk received from the stream. This caused significant performance bottlenecks and race conditions in Flutter's rendering pipeline.

  2. Optimized Widget Reconciliation and State Management:
    Unique Keys: Added unique ValueKeys to MessageBubble widgets within ChatMessageContent. This ensures Flutter's reconciliation algorithm can correctly identify and update widgets during rebuilds, preventing unnecessary tree mutations.
    Lifecycle-Aware Caching in Markit 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.

Issue screenshot:
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions