rrousselGit / flutter_hooks

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.
MIT License
3.07k stars 175 forks source link

add useListenableSelector #308

Closed ronnieeeeee closed 2 years ago

ronnieeeeee commented 2 years ago

Hi, Remi!

useListenable is easy to use, but I think it tends to cause unnecessary rebuilds In such a case, I think the useListenableSelector added this time is convenient.

This is an example where the button is disabled when nothing is entered in TextField.

Example using useListenable.

Widget build(BuildContext context) {
    var ctrl = useTextEditingController();
    useListenable(ctrl);
    return Column(
      children: [
        TextField(
          controller: ctrl,
        ),
        ElevatedButton(
            onPressed: ctrl.text.isNotEmpty ? () => print("Pressed!") : null,
            child: Text("Button")),
      ],
    );
  }

Example using useListenableSelector. This is the better performance.

 Widget build(BuildContext context) {
    final ctrl = useTextEditingController();
    final bool isNotEmpty =
        useListenableSelector(ctrl, () => ctrl.text.isNotEmpty);
    return Column(
      children: [
        TextField(controller: ctrl),
        ElevatedButton(
            // If no text is entered, the button cannot be pressed
            onPressed: isNotEmpty ? () => print("Pressed!") : null,
            child: Text("Button")),
      ],
    );
  }
codecov[bot] commented 2 years ago

Codecov Report

Merging #308 (911aff4) into master (8c68676) will increase coverage by 0.07%. The diff coverage is 100.00%.

@@            Coverage Diff             @@
##           master     #308      +/-   ##
==========================================
+ Coverage   98.17%   98.25%   +0.07%     
==========================================
  Files          13       14       +1     
  Lines         659      689      +30     
==========================================
+ Hits          647      677      +30     
  Misses         12       12              
Impacted Files Coverage Δ
...ges/flutter_hooks/lib/src/listenable_selector.dart 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 8c68676...911aff4. Read the comment docs.

rrousselGit commented 2 years ago

Thanks!