How can I see what is causing my widgets to keep propagating the widget tree? I'm using the Provider package and experiencing a problem where the widgets keep stacking up - for example, if I add a print statement to the homepage:
@override
Widget build(BuildContext context) {
print("Home");
Then after navigating around the app for a while, if I clear the debug console and load the homepage or any screens below it, I will get multiple "Home" printouts, ie:
flutter: Home
flutter: Home
flutter: Home
flutter: Home
flutter: Home
flutter: Home
The more I navigate around the app, the more they stack up. What would be the correct way to debug this?
You can use Flutter's devtools https://flutter.dev/docs/development/tools/devtools/overview
It possesses a few helpful screens such as:
This screen includes a detailed tree of the widgets that rebuilt within the given time frame.
The "Flutter Performance" tool displays widget rebuilds in real-time as you interact with the app, in Debug mode.
From its documentation (same URL as above):
The exact count of the rebuilds for this frame displays in the second column from the right. For a high number of rebuilds, a yellow spinning circle displays. The column to the far right shows how many times a widget was rebuilt since entering the current screen. For widgets that aren’t rebuilt, a solid grey circle displays. Otherwise, a grey spinning circle displays.
The linked page includes further profiling tips, notably:
Note that numerous rebuilds doesn’t necessarily indicate a problem. Typically you should only worry about excessive rebuilds if you have already run the app in profile mode and verified that the performance is not what you want.
Personally and on a more educational level, watching the rebuild behavior in real-time while interacting with UI has helped me grasp specific Flutter widgets and mechanisms.
As of December 2019 this tool is only available on the Flutter plugins for Android Studio and IntelliJ.
Try the BuildTracker
from https://pub.dev/packages/debug_tools
It allows to track stack traces that lead to widgets being marked dirty and hence causing rebuilds.
Example run:
ValueListenableBuilder<String> ← [root]
Directionality ← ValueListenableBuilder<String> ← [root]
Text ← Directionality ← ValueListenableBuilder<String> ← [root]
State.setState package:flutter/src/widgets/framework.dart 1287:15
_ValueListenableBuilderState._valueChanged package:flutter/src/widgets/value_listenable_builder.dart 182:5
ChangeNotifier.notifyListeners package:flutter/src/foundation/change_notifier.dart 243:25
ValueNotifier.value= package:flutter/src/foundation/change_notifier.dart 309:5
* main.<fn> test/build_tracker_test.dart 25:10
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With