noob
a few handy flutter tools, dead simple urirouter
for uri
-based navigator or buildtracker
to track widget rebuilds and what caused them to rebuild.
urirouter
dead simple uri
-based page router.
class bookspage extends statelesswidget {
static final route = uriroute(
path: '/books/:id',
pagebuilder: (context, params) => bookspage(id: params.pathparams['id']!),
);
static string path(string id) => route.build(pathparams: <string, string>{'id': id});
...
}
final router = urirouter(routes: [
bookspage.route,
]);
runapp(materialapp(ongenerateroute: router.generateroute));
navigator.pushnamed(context, bookspage.path('42'));
hooks
some handy hooks:
usedisposable
: manage objects that need to be disposeduserebuild
: manually trigger rebuilding of ahookwidet
/hookbuilder
usevariable
: lightweight hook to create a variable (mutable value) that doesn’t trigger rebuilds when it’s changeduselistener
/usevaluelistener
: attach a callback tolistenable
/valuelistenable
without triggering rebuilds when they get notifieduseasyncvalue
: turnfuture
intoasyncvalue
uselastvalidasyncdata
: remember most recent validasyncdata
providers
some handy providers:
lastpointereventprovider
: track the last[pointerevent
s of active pointersglobalpositionprovider
: track the global position of abuildcontext
srenderbox
pointerindicator
pointerindicator(child: ...)
the pointerindicator
shows positions of pointerevent
s and hence allows to record the screen including “fingers”.
buildtracker
void main() {
// initialize `trackingbuildownerwidgetsflutterbinding` to enable tracking
trackingbuildownerwidgetsflutterbinding.ensureinitialized();
// initialize `buildtracker`
final tracker = buildtracker(printbuildframeincluderebuilddirtywidget: false);
// print top 10 stacks leading to rebuilds every 10 seconds
timer.periodic(const duration(seconds: 10), (_) => tracker.printtopschedulebuildforstacks());
// run
runapp(...);
}
a lot of people have spent hours in trying to figure out why flutter constantly rebuilds dozens of widgets in their app. to the rescue, buildtracker
allows to track which widgets are rebuilt during every frame and — even more important — what caused them to rebuild.
flutter’s rendering pipeline is usually idle until some widget in the widget tree is marked as dirty, e.g. by calling setstate
on the state
of a statefulwidget
. in that case, flutter will schedule the widget to be build during the next frame. however, before the next frame is actually being built, there might be many more widgets being marked dirty. all these widgets we call the “build roots” of the succeeding frame.
when flutter is eventually building the next frame, it starts by building the build roots and these might trigger builds of more widgets as the process is recursively trickling down the widget tree.
for each frame, buildtracker
prints all widgets that were rebuilt and the stack traces for each of the build roots.
consider the following example test-case:
void main() {
trackingbuildownerautomatedtestwidgetsflutterbinding.ensureinitialized();
final tracker = buildtracker(enabled: false);
testwidgets('test build frames', (tester) async {
tracker.enabled = true;
final text = valuenotifier('');
debugprint('# `tester.pumpwidget(...)`');
debugprint('');
await tester.pumpwidget(
valuelistenablebuilder<string>(
valuelistenable: text,
builder: (_, value, child) => directionality(
textdirection: textdirection.ltr,
child: text(value),
),
),
);
debugprint("# looping `text.value`");
debugprint('');
for (var i = 0; i < 10; i++) {
text.value = '$i';
await tester.pump();
}
debugprint('# test end');
debugprint('');
tracker.enabled = false;
tracker.printtopschedulebuildforstacks();
});
}
if we run the example, buildtracker
generates markdown-formatted logs that contain rebuilt and dirty widgets. the full output can be found here.
for example, after text.value = '0'
, we have:
widgets that were built
[root]
valuelistenablebuilder<string> ← [root]
directionality ← valuelistenablebuilder<string> ← [root]
text ← directionality ← valuelistenablebuilder<string> ← [root]
widgets that were marked dirty (build roots)
[root]:
stack trace #1beada3:
element.markneedsbuild package:flutter/src/widgets/framework.dart 4157:12
renderobjecttowidgetadapter.attachtorendertree package:flutter/src/widgets/binding.dart 1102:15
widgetsbinding.attachrootwidget package:flutter/src/widgets/binding.dart 934:7
widgettester.pumpwidget.<fn> package:flutter_test/src/widget_tester.dart 520:15
_customzone.run dart:async
testasyncutils.guard package:flutter_test/src/test_async_utils.dart 72:41
widgettester.pumpwidget package:flutter_test/src/widget_tester.dart 519:27
* main.<fn> test/build_tracker_test.dart 17:18
hence, we can easily spot that test/build_tracker_test.dart 25:10
was the actual location that triggered the frame, which is text.value = '0'
.
furthermore, calling buildtracker.printtopschedulebuildforstacks
prints the top stack traces resulting in rebuids:
top 10 schedulebuildfor
stack traces (build roots)
10 times:
stack trace #16e7ece8:
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 30:12
...
1 times:
stack trace #1beada3:
element.markneedsbuild package:flutter/src/widgets/framework.dart 4157:12
renderobjecttowidgetadapter.attachtorendertree package:flutter/src/widgets/binding.dart 1102:15
widgetsbinding.attachrootwidget package:flutter/src/widgets/binding.dart 934:7
widgettester.pumpwidget.<fn> package:flutter_test/src/widget_tester.dart 520:15
_customzone.run dart:async
testasyncutils.guard package:flutter_test/src/test_async_utils.dart 72:41
widgettester.pumpwidget package:flutter_test/src/widget_tester.dart 519:27
* main.<fn> test/build_tracker_test.dart 17:18
...
periodiclistenable
final timer30 = usedisposable<periodiclistenable>(() => periodiclistenable(const duration(seconds: 30)), (_) => _.dispose());
uselistener(timer60, callinitially: false, callback: () => context.refresh(daaprovider));
periodiclistenable
can be used to create a listenable
that notifies its listeners periodically.
Comments are closed.