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

build
pub
codecov

binder

logo

a lightweight, yet powerful way to bind your application state with your business logic.

the vision

as other state management pattern, binder aims to separate the application state from the business logic that updates it:

data flow

we can see the whole application state as the agglomeration of a multitude of tiny states. each state being independent from each other.
a view can be interested in some particular states and has to use a logic component to update them.

getting started

installation

in the pubspec.yaml of your flutter project, add the following dependency:

dependencies:
  binder: <latest_version>

in your library add the following import:

import 'package:binder/binder.dart';

basic usage

any state has to be declared through a stateref with its initial value:

final counterref = stateref(0);

note: a state should be immutable, so that the only way to update it, is through methods provided by this package.

any logic component has to be declared through a logicref with a function that will be used to create it:

final counterviewlogicref = logicref((scope) => counterviewlogic(scope));

the scope argument can then be used by the logic to mutate the state and access other logic components.

note: you can declare stateref and logicref objects as public global variables if you want them to be accessible from other parts of your app.

if we want our counterviewlogic to be able to increment our counter state, we might write something like this:

/// a business logic component can apply the [logic] mixin to have access to
/// useful methods, such as `write` and `read`.
class counterviewlogic with logic {
  const counterviewlogic(this.scope);

  /// this is the object which is able to interact with other components.
  @override
  final scope scope;

  /// we can use the [write] method to mutate the state referenced by a
  /// [stateref] and [read] to obtain its current state.
  void increment() => write(counterref, read(counterref) + 1);
}

in order to bind all of this together in a flutter app, we have to use a dedicated widget called binderscope.
this widget is responsible for holding a part of the application state and for providing the logic components.
you will typically create this widget above the materialapp widget:

binderscope(
  child: materialapp(
    home: counterview(),
  ),
);

in any widget under the binderscope, you can call extension methods on buildcontext to bind the view to the application state and to the business logic components:

class counterview extends statelesswidget {
  const counterview({key? key}) : super(key: key);

  @override
  widget build(buildcontext context) {
    /// we call the [watch] extension method on a [stateref] to rebuild the
    /// widget when the underlaying state changes.
    final counter = context.watch(counterref);

    return scaffold(
      appbar: appbar(title: const text('binder example')),
      body: center(
        child: column(
          mainaxisalignment: mainaxisalignment.center,
          children: <widget>[
            const text('you have pushed the button this many times:'),
            text('$counter', style: theme.of(context).texttheme.headline4),
          ],
        ),
      ),
      floatingactionbutton: floatingactionbutton(
        /// we call the [use] extension method to get a business logic component
        /// and call the appropriate method.
        onpressed: () => context.use(counterviewlogicref).increment(),
        tooltip: 'increment',
        child: const icon(icons.add),
      ),
    );
  }
}

this is all you need to know for a basic usage.

note: the whole code for the above snippets is available in the example file.


intermediate usage

select

a state can be of a simple type as an int or a string but it can also be more complex, such as the following:

class user {
  const user(this.firstname, this.lastname, this.score);

  final string firstname;
  final string lastname;
  final int score;
}

some views of an application are only interested in some parts of the global state. in these cases, it can be more efficient to select only the part of the state that is useful for these views.

for example, if we have an app bar title which is only responsible for displaying the full name of a user, and we don’t want it to rebuild every time the score changes, we will use the select method of the stateref to watch only a sub part of the state:

class appbartitle extends statelesswidget {
  const appbartitle({key? key}) : super(key: key);

  @override
  widget build(buildcontext context) {
    final fullname = context.watch(
      userref.select((user) => '${user.firstname} ${user.lastname}'),
    );
    return text(fullname);
  }
}

consumer

if you want to rebuild only a part of your widget tree and don’t want to create a new widget, you can use the consumer widget.
this widget can take a watchable (a stateref or even a selected state of a stateref).

class myappbar extends statelesswidget {
  const myappbar({key? key}) : super(key: key);

  @override
  widget build(buildcontext context) {
    return appbar(
      title: consumer(
        watchable:
            userref.select((user) => '${user.firstname} ${user.lastname}'),
        builder: (context, string fullname, child) => text(fullname),
      ),
    );
  }
}

logicloader

if you want to trigger an asynchronous data load of a logic, from the widget side, logicloader is the widget you need!

to use it, you have to implement the loadable interface in the logic which needs to load data.
then you’ll have to override the load method and fetch the data inside it.

final usersref = stateref(const <user>[]);
final loadingref = stateref(false);

final userslogicref = logicref((scope) => userslogic(scope));

class userslogic with logic implements loadable {
  const userslogic(this.scope);

  @override
  final scope scope;

  usersrepository get _usersrepository => use(usersrepositoryref);

  @override
  future<void> load() async {
    write(loadingref, true);
    final users = await _usersrepository.fetchall();
    write(usersref, users);
    write(loadingref, false);
  }
}

from the widget side, you’ll have to use the logicloader and provide it the logic references you want to load:

class home extends statelesswidget {
  const home({
    key? key,
  }) : super(key: key);

  @override
  widget build(buildcontext context) {
    return logicloader(
      refs: [userslogicref],
      child: const usersview(),
    );
  }
}

you can watch the state in a subtree to display a progress indicator when the data is fetching:

class usersview extends statelesswidget {
  const usersview({
    key? key,
  }) : super(key: key);

  @override
  widget build(buildcontext context) {
    final loading = context.watch(loadingref);
    if (loading) {
      return const circularprogressindicator();
    }

    // display the users in a list when have been fetched.
    final users = context.watch(usersref);
    return listview(...);
  }
}

alternatively, you can use the builder parameter to achieve the same goal:

class home extends statelesswidget {
  const home({
    key? key,
  }) : super(key: key);

  @override
  widget build(buildcontext context) {
    return logicloader(
      refs: [userslogicref],
      builder: (context, loading, child) {
        if (loading) {
          return const circularprogressindicator();
        }

        // display the users in a list when have been fetched.
        final users = context.watch(usersref);
        return listview();
      },
    );
  }
}

overrides

it can be useful to be able to override the initial state of stateref or the factory of logicref in some conditions:

  • when we want a subtree to have its own state/logic under the same reference.
  • for mocking values in tests.
reusing a reference under a different scope.

let’s say we want to create an app where a user can create counters and see the sum of all counters:

counters

we could do this by having a global state being a list of integers, and a business logic component for adding counters and increment them:

final countersref = stateref(const <int>[]);

final counterslogic = logicref((scope) => counterslogic(scope));

class counterslogic with logic {
  const counterslogic(this.scope);

  @override
  final scope scope;

  void addcounter() {
    write(countersref, read(countersref).tolist()..add(0));
  }

  void increment(int index) {
    final counters = read(countersref).tolist();
    counters[index]++;
    write(countersref, counters);
  }
}

we can then use the select extension method in a widget to watch the sum of this list:

final sum = context.watch(countersref.select(
  (counters) => counters.fold<int>(0, (a, b) => a + b),
));

now, for creating the counter view, we can have an index parameter in the constructor of this view.
this has some drawbacks:

  • if a child widget needs to access this index, we would need to pass the index for every widget down the tree, up to our child.
  • we cannot use the const keyword anymore.

a better approach would be to create a binderscope above each counter widget. we would then configure this binderscope to override the state of a stateref for its descendants, with a different initial value.

any stateref or logicref can be overriden in a binderscope. when looking for the current state, a descendant will get the state of the first reference overriden in a binderscope until the root binderscope.
this can be written like this:

final indexref = stateref(0);

class homeview extends statelesswidget {
  @override
  widget build(buildcontext context) {
    final counterscount =
        context.watch(countersref.select((counters) => counters.length));

    return scaffold(
     ...
      child: gridview(
        ...
        children: [
          for (int i = 0; i < counterscount; i++)
            binderscope(
              overrides: [indexref.overridewith(i)],
              child: const counterview(),
            ),
        ],
      ),
     ...
    );
  }
}

the binderscope constructor has an overrides parameter which can be supplied from an overridewith method on stateref and logicref instances.

note: the whole code for the above snippets is available in the example file.

mocking values in tests

let’s say you have an api client in your app:

final apiclientref = logicref((scope) => apiclient());

if you want to provide a mock instead, while testing, you can do:

testwidgets('test your view by mocking the api client', (tester) async {
  final mockapiclient = mockapiclient();

  // build our app and trigger a frame.
  await tester.pumpwidget(
    binderscope(
      overrides: [apiclientref.overridewith((scope) => mockapiclient)],
      child: const myapp(),
    ),
  );

  expect(...);
});

whenever the apiclientref is used in your app, the mockapiclient instance will be used instead of the real one.


advanced usage

computed

you may encounter a situation where different widgets are interested in a derived state which is computed from different sates. in this situation it can be helpful to have a way to define this derived state globally, so that you don’t have to copy/paste this logic across your widgets.
binder comes with a computed class to help you with that use case.

let’s say you have a list of products referenced by productsref, each product has a price, and you can filter these products according to a price range (referenced by minpriceref and maxpriceref).

you could then define the following computed instance:

final filteredproductsref = computed((watch) {
  final products = watch(productsref);
  final minprice = watch(minpriceref);
  final maxprice = watch(maxpriceref);

  return products
      .where((p) => p.price >= minprice && p.price <= maxprice)
      .tolist();
});

like stateref you can watch a computed in the build method of a widget:

@override
widget build(buildcontext context) {
  final filteredproducts = context.watch(filteredproductsref);
  ...
  // do something with `filteredproducts`.
}

note: the whole code for the above snippets is available in the example file.

observers

you may want to observe when the state changed and do some action accordingly (for example, logging state changes).
to do so, you’ll need to implement the stateobserver interface (or use a delegatingstateobserver) and provide an instance to the observers parameter of the binderscope constructor.

bool onstateupdated<t>(stateref<t> ref, t oldstate, t newstate, object action) {
  logs.add(
    '[${ref.key.name}#$action] changed from $oldstate to $newstate',
  );

  // indicates whether this observer handled the changes.
  // if true, then other observers are not called.
  return true;
}
...
binderscope(
  observers: [delegatingstateobserver(onstateupdated)],
  child: const subtree(),
);

undo/redo

binder comes with a built-in way to move in the timeline of the state changes.
to be able to undo/redo a state change, you must add a mementoscope in your tree.
the mementoscope will be able to observe all changes made below it:

return mementoscope(
  child: builder(builder: (context) {
    return materialapp(
      home: const myhomepage(),
    );
  }),
);

then, in a business logic, stored below the mementoscope, you will be able to call undo/redo methods.

note: you will get an assertionerror at runtime if you don’t provide a mementoscope above the business logic calling undo/redo.

disposable

in some situation, you’ll want to do some action before the binderscope hosting a business logic component, is disposed. to have the chance to do this, your logic will need to implement the disposable interface.

class mylogic with logic implements disposable {
  void dispose(){
    // do some stuff before this logic go away.
  }
}

statelistener

if you want to navigate to another screen or show a dialog when a state change, you can use the statelistener widget.

for example, in an authentication view, you may want to show an alert dialog when the authentication failed.
to do it, in the logic component you could set a state indicating whether the authentication succeeded or not, and have a statelistener in your view do respond to these state changes:

return statelistener(
  watchable: authenticationresultref,
  onstatechanged: (context, authenticationresult state) {
    if (state is authenticationfailure) {
      showdialog<void>(
        context: context,
        builder: (context) {
          return alertdialog(
            title: const text('error'),
            content: const text('authentication failed'),
            actions: [
              textbutton(
                onpressed: () => navigator.of(context).pop(),
                child: const text('ok'),
              ),
            ],
          );
        },
      );
    } else {
      navigator.of(context).pushreplacementnamed(route_names.home);
    }
  },
  child: child,
);

in the above snippet, each time the state referenced by authenticationresultref changes, the onstatechanged callback is fired. in this callback we simply verify the type of the state to determine whether we have to show an alert dialog or not.

dartdev tools

binder wants to simplify the debugging of your app. by using the dartdev tools, you will be able to inspect the current states hosted by any binderscope.


snippets

you can find code snippets for vscode at snippets.

sponsoring

i’m working on my packages on my free-time, but i don’t have as much time as i would. if this package or any other package i created is helping you, please consider to sponsor me so that i can take time to read the issues, fix bugs, merge pull requests and add features to these packages.

contributions

feel free to contribute to this project.

if you find a bug or want a feature, but don’t know how to fix/implement it, please fill an issue.
if you fixed a bug or implemented a feature, please send a pull request.


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.