reactives
a new way for flutter to reuse/group common logic. think of them like react hooks but for and of flutter.
idea copied from the lit world
motive
have you ever written code like this?
class awesomewidget extends statefulwidget {
const awesomewidget({key? key}) : super(key: key);
@override
_awesomewidgetstate createstate() => _awesomewidgetstate();
}
class _awesomewidgetstate extends state<awesomewidget>
with tickerproviderstatemixin {
late final texteditingcontroller emailctrl;
late final texteditingcontroller passwordctrl;
late final animationcontroller entryanimation;
late final animationcontroller highlightanimation;
@override
void initstate() {
super.initstate();
emailctrl = texteditingcontroller();
passwordctrl = texteditingcontroller();
entryanimation = animationcontroller(vsync: this);
highlightanimation = animationcontroller(vsync: this);
}
@override
void dispose() {
emailctrl.dispose();
entryanimation.dispose();
highlightanimation.dispose();
passwordctrl.dispose();
super.dispose();
}
@override
widget build(buildcontext context) {
return container();
}
}
there are a couple of problems here.
- most of the object management logic is generic and can be reused.
- it is extremely easy to forget that one
dispose
call (confession). - coupling the logic to the widget makes it harder to test.
using reactives this gets transformed to,
class awesomereactivewidget extends statefulwidget {
const awesomereactivewidget({key? key}) : super(key: key);
@override
_awesomereactivewidgetstate createstate() => _awesomereactivewidgetstate();
}
class _awesomereactivewidgetstate extends state<awesomereactivewidget> with reactivehostmixin {
late final emailctrl = reactivetexteditingcontroller(this);
late final passwordctrl = reactivetexteditingcontroller(this);
late final entryanimation = reactiveanimationcontroller(this);
late final exitanimation = reactiveanimationcontroller(this);
@override
widget build(buildcontext context) {
return container(
// ....
);
}
}
see examples for examples of writing a reactive or just browse the source, it’s really small.
comparision to flutter_hooks:
from a user perspective flutter_hooks
is a replacement for statefulwidget
. reactives
is not. if you look at the code for reactivehostmixin
it is about 60 lines (blank lines included). reactives do not try to replace statefulwidget
, it just solves the reusability problem inherent due to mixin’s “is-a” relationship. reactives have a “has-a” relationship.
there are no new rules to writing reactives. see examples of existing reactives. it is basically the same logic isolated in a different class.
for the same reason it doesn’t need a lot of the hooks like usestate
which would be needed if tried to replace statefulwidget
.
the learning curve of reactives is next to negligible. hooks need you to learn a few concepts and how to/not to do things. it also requires you to transform entire widgets. reactives can be adapted incrementally even for a single widget.
Comments are closed.