Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

implementation hooks

hooks are a new kind of object that manages a widget life-cycles. they exist for one reason: increase the code sharing between widgets and as a complete replacement for statefulwidget.

react hooks for flutter. hooks are a new kind of object that manages a widget life-cycles. they are used to increase code sharing between widgets and as a complete replacement for statefulwidget.

motivation

statefulwidget suffer from a big problem: it is very difficult to reuse the logic of say initstate or dispose. an obvious example is animationcontroller:

class example extends statefulwidget {
  final duration duration;

  const example({key key, @required this.duration})
      : assert(duration != null),
        super(key: key);

  @override
  _examplestate createstate() => _examplestate();
}

class _examplestate extends state<example> with singletickerproviderstatemixin {
  animationcontroller _controller;

  @override
  void initstate() {
    super.initstate();
    _controller = animationcontroller(vsync: this, duration: widget.duration);
  }

  @override
  void didupdatewidget(example oldwidget) {
    super.didupdatewidget(oldwidget);
    if (widget.duration != oldwidget.duration) {
      _controller.duration = widget.duration;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  widget build(buildcontext context) {
    return container();
  }
}

all widgets that desire to use an animationcontroller will have to reimplement almost all of this from scratch, which is of course undesired.

dart mixins can partially solve this issue, but they suffer from other problems:

  • a given mixin can only be used once per class.
  • mixins and the class shares the same object. this means that if two mixins define a variable under the same name, the end result may vary between compilation fail to unknown behavior.

this library propose a third solution:

class example extends hookwidget {
  final duration duration;

  const example({key key, @required this.duration})
      : assert(duration != null),
        super(key: key);

  @override
  widget build(buildcontext context) {
    final controller = useanimationcontroller(duration: duration);
    return container();
  }
}

this code is strictly equivalent to the previous example. it still disposes the animationcontroller and still updates its duration when example.duration changes.
but you’re probably thinking:

where did all the logic go?

that logic moved into useanimationcontroller, a function included directly in this library (see https://github.com/rrousselgit/flutter_hooks#existing-hooks). it is what we call a hook.

hooks are a new kind of objects with some specificities:

  • they can only be used in the build method of a hookwidget.
  • the same hook is reusable an infinite number of times
    the following code defines two independent animationcontroller, and they are correctly preserved when the widget rebuild.
widget build(buildcontext context) {
  final controller = useanimationcontroller();
  final controller2 = useanimationcontroller();
  return container();
}
  • hooks are entirely independent of each other and from the widget. which means they can easily be extracted into a package and published on pub for others to use.

principle

similarly to state, hooks are stored on the element of a widget. but instead of having one state, the element stores a list<hook>. then to use a hook, one must call hook.use.

the hook returned by use is based on the number of times it has been called. the first call returns the first hook; the second call returns the second hook, the third returns the third hook, …

if this is still unclear, a naive implementation of hooks is the following:

class hookelement extends element {
  list<hookstate> _hooks;
  int _hookindex;

  t use<t>(hook<t> hook) => _hooks[_hookindex++].build(this);

  @override
  performrebuild() {
    _hookindex = 0;
    super.performrebuild();
  }
}

for more explanation of how they are implemented, here’s a great article about how they did it in react: https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e

rules

due to hooks being obtained from their index, there are some rules that must be respected:

do call use unconditionally

widget build(buildcontext context) {
  hook.use(myhook());
  // ....
}

don’t wrap use into a condition

widget build(buildcontext context) {
  if (condition) {
    hook.use(myhook());
  }
  // ....
}

do always call all the hooks:

widget build(buildcontext context) {
  hook.use(hook1());
  hook.use(hook2());
  // ....
}

don’t aborts build method before all hooks have been called:

widget build(buildcontext context) {
  hook.use(hook1());
  if (condition) {
    return container();
  }
  hook.use(hook2());
  // ....
}

about hot-reload

since hooks are obtained from their index, one may think that hot-reload while refactoring will break the application.

but worry not, hookwidget overrides the default hot-reload behavior to work with hooks. still, there are some situations in which the state of a hook may get reset.

consider the following list of hooks:

hook.use(hooka());
hook.use(hookb(0));
hook.use(hookc(0));

then consider that after a hot-reload, we edited the parameter of hookb:

hook.use(hooka());
hook.use(hookb(42));
hook.use(hookc());

here everything works fine; all hooks keep their states.

now consider that we removed hookb. we now have:

hook.use(hooka());
hook.use(hookc());

in this situation, hooka keeps its state but hookc gets a hard reset.
this happens because when a refactoring is done, all hooks after the first line impacted are disposed. since hookc was placed after hookb, is got disposed.

how to use

there are two ways to create a hook:

  • a function

functions are by far the most common way to write a hook. thanks to hooks being composable by nature, a function will be able to combine other hooks to create a custom hook. by convention, these functions will be prefixed by use.

the following defines a custom hook that creates a variable and logs its value on the console whenever the value changes:

valuenotifier<t> useloggedstate<t>(buildcontext context, [t initialdata]) {
  final result = usestate<t>(initialdata);
  usevaluechanged(result.value, (_, __) {
    print(result.value);
  });
  return result;
}
  • a class

when a hook becomes too complex, it is possible to convert it into a class that extends hook, which can then be used using hook.use. as a class, the hook will look very similar to a state and have access to life-cycles and methods such as inithook, dispose and setstate. it is usually a good practice to hide the class under a function as such:

result usemyhook(buildcontext context) {
  return hook.use(_myhook());
}

the following defines a hook that prints the time a state has been alive.

class _timealive<t> extends hook<void> {
  const _timealive();

  @override
  _timealivestate<t> createstate() => _timealivestate<t>();
}

class _timealivestate<t> extends hookstate<void, _timealive<t>> {
  datetime start;

  @override
  void inithook() {
    super.inithook();
    start = datetime.now();
  }

  @override
  void build(buildcontext context) {
    // this hook doesn't create anything nor uses other hooks
  }

  @override
  void dispose() {
    print(datetime.now().difference(start));
    super.dispose();
  }
}

existing hooks

flutter_hooks comes with a list of reusable hooks already provided.

they are divided in different kinds:

primitives

a set of low level hooks that interacts with the different life-cycles of a widget

name description
useeffect useful for side-effects and optionally canceling them.
usestate create variable and subscribes to it.
usememoized cache the instance of a complex object.
usecontext obtain the buildcontext of the building hookwidget.
usevaluechanged watches a value and calls a callback whenever the value changed.

object binding

this category of hooks allows manipulating existing flutter/dart objects with hooks.
they will take care of creating/updating/disposing an object.

dart:async related:

name description
usestream subscribes to a stream and return its current state in an asyncsnapshot.
usestreamcontroller creates a streamcontroller automatically disposed.
usefuture subscribes to a future and return its current state in an asyncsnapshot.

animation related:

name description
usesingletickerprovider creates a single usage tickerprovider.
useanimationcontroller creates an animationcontroller automatically disposed.
useanimation subscribes to an animation and return its value.

listenable related:

name description
uselistenable subscribes to a listenable and mark the widget as needing build whenever the listener is called.
usevaluenotifier creates a valuenotifier automatically disposed.
usevaluelistenable subscribes to a valuelistenable and return its value.

misc

a series of hooks with no particular theme.

name description
usereducer an alternative to usestate for more complex states.
useprevious returns the previous argument called to [useprevious].

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.