useEffect function
Useful for side-effects and optionally canceling them.
useEffect is called synchronously on every build
, unless
keys
is specified. In which case useEffect is called again only if
any value inside keys
has changed.
It takes an effect
callback and calls it synchronously.
That effect
may optionally return a function, which will be called when the effect
is called again or if the widget is disposed.
By default effect
is called on every build
call, unless keys
is specified.
In which case, effect
is called once on the first useEffect call and whenever something within keys
change/
The following example call useEffect to subscribes to a Stream and cancels the subscription when the widget is disposed. Also if the Stream changes, it will cancel the listening on the previous Stream and listen to the new one.
Stream stream;
useEffect(() {
final subscription = stream.listen(print);
// This will cancel the subscription when the widget is disposed
// or if the callback is called again.
return subscription.cancel;
},
// when the stream changes, useEffect will call the callback again.
[stream],
);
Implementation
void useEffect(Dispose? Function() effect, [List<Object?>? keys]) {
use(_EffectHook(effect, keys));
}