rrousselGit / state_notifier

ValueNotifier, but outside Flutter and with some extra perks
MIT License
311 stars 28 forks source link

Added an optional builder condition #38

Closed elias8 closed 4 years ago

elias8 commented 4 years ago

Added a buildWhen callback to determine a StateNotifierBuilder should rebuild or not. By default, the StateNotifierBuilder it will always rebuild.

A simple example would be if you have a counter StateNotifier and you want to rebuild the widget only when the number is even, the code for that will be like this:

StateNotifierBuilder<int>(
    stateNotifier: notifier,
    buildWhen: (state) => state % 2 == 0,
    builder: (context, value, c) {
      return Text('$value', textDirection: TextDirection.ltr);
    },
    child: child,
)
codecov[bot] commented 4 years ago

Codecov Report

Merging #38 into master will decrease coverage by 0.32%. The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master      #38      +/-   ##
==========================================
- Coverage   90.28%   89.95%   -0.33%     
==========================================
  Files           4        4              
  Lines         350      229     -121     
==========================================
- Hits          316      206     -110     
+ Misses         34       23      -11     
Impacted Files Coverage Δ
...ter_state_notifier/lib/flutter_state_notifier.dart 100.00% <100.00%> (+1.88%) :arrow_up:
example/lib/main.dart 38.70% <0.00%> (-50.86%) :arrow_down:
example/lib/my_state_notifier.dart 80.00% <0.00%> (+27.36%) :arrow_up:
rrousselGit commented 4 years ago

I'm not fond of the buildWhen idea. That is too easy to get wrong and not flexible enough.

I'd suggest using provider instead, and do:

StateNotifierProvider<Counter, int>(
  create: (_) => Counter(),
  builder: (context, child) {
    final isOdd = context.select((int v) => v.isOdd));
    return Text('$isOdd');
  },
),
rrousselGit commented 4 years ago

Closing as the recommended solution is instead to use provider/riverpod