Why?
For work i use react and i hate writing class components, so i immediately go crazy when hooks have been announced and with their obscure-magic allow functional components to use state and side-effect.
When hooks will be allowed for production code, in React, i will be able only to write functional component and avoid the verbosity of classes. Plus i can share stateful logic between components without use the orribles mixins, redux, or other external library and unfamiliar patterns.
Now i use Flutter for a personal project, so i start to implementing something similar to react hooks for avoid writing classes.
Initially when i start using flutter i try avoiding classes using only functions
final StatefulWidgetBuilder HelloWorld = (context, setState) {
...,
}
and using them as builder function in a StatefulBuilder.
But i can't dispose things, for example stream subscription. Essentially i can't dispose side-effects.
So i start thinking in another way, i create an HookBuilder, with a StatefulBuilder implementation.
Before build, StatefulBuilder, initialize an HookContext and on dispose, dispose all registered Hook.
I define an use function how consume an HookTransformer function, store the result in the hooks store and return the value.
Using use i define useMemo, useCallback, useState, and later useEffect.
So now i can write in my code something like React functional hooked component.
final StatefulWidgetBuilder HelloWorld = (context) {
final name = useState('');
final nameInfo = useAsync(getUserInfo, null, [name]);
...
}
and using them as builder function in my StatefulBuilder.
...
return StatefulBuilder(builder: HelloWorld);
I'm now using it for week, so i decided to split the code and release my implementation of hooks as flutter package and on github flhooks.
Take a look to it.
Top comments (0)