Description
Steps to reproduce
Description:
When the soft keyboard is opened or closed in a Flutter application, it triggers a rebuild of all the pages in the Navigator stack. While individual widgets may be lightweight, this behavior can lead to significant performance degradation in complex applications, especially when multiple pages are cached in the stack.
This issue becomes particularly problematic in scenarios where:
The application has a deep Navigator stack with multiple cached pages.
Pages contain complex widget trees or perform heavy computations during rebuilds.
Frequent keyboard interactions are required, such as in forms or chat applications.
The root cause of this behavior is the change in MediaQuery values (e.g., MediaQuery.of(context).viewInsets) when the keyboard is shown or hidden. This change propagates through the widget tree, causing unnecessary rebuilds of widgets that are not directly affected by the keyboard.
Expected Behavior:
Only the widgets directly impacted by the keyboard (e.g., those relying on MediaQuery.viewInsets) should rebuild.
Pages in the Navigator stack that are not visible or do not depend on MediaQuery changes should remain unaffected.
Actual Behavior:
All pages in the Navigator stack rebuild when the keyboard is opened or closed, even if they are not visible or do not rely on MediaQuery values.
This results in unnecessary performance overhead, especially in applications with complex or deeply nested widget trees.
Steps to Reproduce:
Create a Flutter application with a Navigator stack containing multiple pages.
Add a TextField to one of the pages to trigger the soft keyboard.
Open and close the keyboard while monitoring the rebuilds of all pages in the stack.
Potential Solutions:
Use MediaQueryData.viewInsets selectively to update only the widgets that depend on keyboard insets.
Implement caching mechanisms or InheritedWidget patterns to minimize unnecessary rebuilds.
Explore using AutomaticKeepAliveClientMixin or other state-preserving techniques to optimize performance.
Impact:
This issue can severely impact the performance of Flutter applications with complex navigation stacks, leading to poor user experience and increased resource consumption.
Code sample
Code sample
[Paste your code here]
What target platforms are you seeing this bug on?
Android
OS/Browser name and version | Device information
Environment: Android
Flutter version: 3.32.2
Device: Any
Does the problem occur on emulator/simulator as well as on physical devices?
Unknown
Logs
No response
Flutter Doctor output
[✓] Flutter (Channel stable, 3.32.2, on macOS 15.3.2 24D81 darwin-arm64, locale
zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 16.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2024.1.5)
[✓] Connected device (3 available)