Flutter Hooks: Say goodbye to StatefulWidget and write better code with less boilerplate. Hooks are a new way to manage state in Flutter that is more concise and efficient. Learn everything you need to know to get started with Flutter Hooks in this comprehensive guide.

Flutter hooks have been available for a while now but they didn’t get a lot of love or visibility since then. I am wondering why, because they are awesome!

In this article I’ll try to show how you can reduce boilerplate and basically remove all the StatefulWidget you’re using today, and also how hooks are easy and cool to use!

First, what are hooks and where do they come from? Anyone?

Okay so they came originally from React (see https://medium.com/@dan_abramov/making-sense-of-react-hooks-fdbde8803889 to know more about them in a React context), I won’t bother you with React as I never used it and probably never will, so it’s not mandatory to know about React at all!

Hooks are a way to share the same code with multiple widgets, code that is usually duplicated or hard to share between stateful widgets. The way I describe them is “Hooks are UI logic management”.


I’ll present you the hooks I use the most in my apps and their stateful widgets equivalent for you to compare both and see what the gain actually is.

Memoized hook:

This hook is a simple way to cache an instance of an object during the lifecycle of your widget. Pretty handy to create your BLoC, MobX store or notifier objects for your screens.

Here is the stateful widget version:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  final store = MyStore();

  _MyHomePageState();

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

And now the hook version:

class MyHomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final store = useMemoized(() => MyStore());
    return Container();
  }
}

Both examples are doing the same job by just creating an instance of MyStore during the lifetime of the widget.

The gain here is not much, but generally you want to initialize your object to load the data for example, and for that Hooks got you covered too. Let’s see useEffect now!

#flutter #ui #dart #hooks

Flutter Hooks: Say Goodbye to StatefulWidgets and Write Better Code
48.25 GEEK