deferrable 1.0.2 copy "deferrable: ^1.0.2" to clipboard
deferrable: ^1.0.2 copied to clipboard

Defer cleanup operations to the `dispose` method of a StatefulWidget

deferrable #

void initState() {
    super.initState();
    _append('time created');
    // Cancel the stream subscription on `dispose()` by calling `defer`
    defer(Stream.periodic(const Duration(seconds: 1))
        .listen((_) => setState(() => date = DateTime.now()))
        .cancel);
  }

Why? #

Add operations to perform in dispose call of StatefulWidget State.

Useful when you're creating things in initState that need to be disposed of in dispose.

Instead of having to store things in private members, and clean up in a different spot in the code, simply call defer and this takes care of the rest.

Example #

class _DeferredTimerWidgetState extends State<DeferredTimerWidget>
    with Deferrable {
  var date = DateTime.now();
  @override
  void initState() {
    super.initState();
    _append('time created');
    defer(Stream.periodic(const Duration(seconds: 1))
        .listen((_) => setState(() => date = DateTime.now()))
        .cancel);
  }

  @override
  Widget build(BuildContext context) => Text(date.toIso8601String());
}

See the example and tests for usage.

2
likes
40
pub points
0%
popularity

Publisher

unverified uploader

Defer cleanup operations to the `dispose` method of a StatefulWidget

Repository (GitHub)
View/report issues

License

BSD-2-Clause (LICENSE)

Dependencies

flutter

More

Packages that depend on deferrable