DEV Community

Alfredo Salzillo
Alfredo Salzillo

Posted on

4 1

React like Hooks for Flutter implementation

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) {
 ...,
}
Enter fullscreen mode Exit fullscreen mode

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]);
  ...
}
Enter fullscreen mode Exit fullscreen mode

and using them as builder function in my StatefulBuilder.

...
return StatefulBuilder(builder: HelloWorld);
Enter fullscreen mode Exit fullscreen mode

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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay