occam 2.0.0-beta.1
occam: ^2.0.0-beta.1 copied to clipboard
Minimalist state management
Occam #
A simple state manager built on native Flutter StatefulWidget, made for my own projects.
Contents #
- Philosophy
- Installation
- Migrating from 1.x
- Quick start
- State manager
- Sharing a controller:
ParentState - Rx types
- Example
- Quality
Philosophy #
There are plenty of state managers, and picking one is hard — each has features you like and others you don't. As a package grows, it tends to accumulate code for things a given project never uses: a dependency full of pieces reinventing the wheel for needs you don't have. This exists because I kept ending up back at one belief: the best abstraction is the one you can hold entirely in your head, six months later, without re-reading its source. Not the one with the most features — the smallest one that's still enough. That's the name: Occam's razor, don't multiply entities beyond necessity.
Every design decision in this package answers to that one question — does this make the mental model bigger, or does it stay the same size? In practice that means:
- Exactly one way to do each thing. One way to hold logic (
StateController), one way to render it (StateWidget), one way to share it with descendants (ParentState), one way to react to a value changing (RxWidget). Never two competing patterns for the same job — every "which do I use here?" is a bit of mental model that didn't need to exist. - A boundary you cannot blur. View and controller are separate classes, not just separate
responsibilities you're trusting yourself to respect. There's no widget-building path with
access to your logic's internals, and no controller method that receives a
BuildContextit isn't explicitly handed — the split is enforced by the type system, not by convention. - Nothing is implicit, except one opt-in. Reactivity only exists where you write
RxWidget; disposal is always the caller's, never automatic; a widget's own controller is handed tobuildas a parameter, never looked up from ambient/global state. The single implicit lookup isParentState, and only when you choose to extend it. If you can't point at the line responsible for a behavior, something is wrong with the library, not with your understanding of it.
Every other section below is that same idea applied to one concrete piece of the API — if something here feels like it's doing more than it needs to, that's a bug in the library, not a feature you're missing.
This started as a package for my own use, so the API can still change between versions — check
CHANGELOG.mdbefore upgrading.
Installation #
dependencies:
occam: ^2.0.0-beta.1
2.0.0 is currently in beta: pub only resolves a prerelease when the constraint names one,
as above. Once 2.0.0 is stable, ^2.0.0 works as usual.
Migrating from 1.x #
2.0.0 has one breaking change: StateWidget.build receives the controller as a parameter,
and the StateWidget.state getter is gone.
// before
Widget build(BuildContext context) { ... state.counter ... }
// after
Widget build(BuildContext context, HomeController state) { ... state.counter ... }
One line per widget, and the compiler points at each one. If the parameter is named state,
the method body compiles unchanged. See CHANGELOG.md for why (a const widget mounted more
than once could read another instance's controller).
Testing the beta: please try it on a screen that mounts the same const widget several
times, and report anything odd in the
issues.
Quick start #
class HomePage extends StateWidget<HomeController> {
const HomePage({super.key});
@override
HomeController createState() => HomeController();
@override
Widget build(BuildContext context, HomeController state) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: state.onButton,
child: const Icon(Icons.add),
),
body: RxWidget<int>(
notifier: state.counter,
builder: (ctx, value) => Text('$value'),
),
);
}
}
class HomeController extends StateController<HomePage> {
final counter = 1.rx;
void onButton() => counter.value++;
@override
void dispose() {
counter.dispose(); // you own disposal of every Rx you create
super.dispose();
}
}
One view (StateWidget), one controller (StateController), one reactive value
(.rx) wrapped in the one widget that rebuilds (RxWidget). That's the whole package —
the rest of this README is those same four pieces in more detail.
State manager #
StateWidget<T> is a StatefulWidget paired with a StateController<T>. The controller for
this instance is passed into build as a parameter — never looked up from ambient state —
so a widget mounted several times (a const banner reused across a page) can never read
another instance's data.
| Hook | When | Use for |
|---|---|---|
initState() |
widget mounted, context not safe | plain field setup |
readyState() |
post-frame after first build, context safe | ModalRoute.of, Theme.of, navigation |
dispose() |
teardown | disposing every Rx you created |
class HomeController extends StateController<HomePage> {
final counter = 1.rx;
void onButton() => counter.value++;
@override
void readyState() {
// Runs after the first frame, so context is safe here — unlike
// initState(). Use it for ModalRoute.of, Theme.of, etc.
}
@override
void dispose() {
counter.dispose();
super.dispose();
}
}
StateController is a regular State, so Flutter's own mixins work on it, e.g.
AutomaticKeepAliveClientMixin to keep a controller alive inside a ListView or
TabBarView (covered by a test).
Sharing a controller: ParentState #
A child that needs an ancestor's controller instead of its own extends ParentState<T>
— the nearest matching StateWidget<T> above it in the tree provides it:
class ChildConsumer extends ParentState<HomeController> {
const ChildConsumer({super.key});
@override
Widget build(BuildContext context, HomeController state) =>
TextButton(onPressed: state.onButton, child: const Text('increment'));
}
Rx types #
RxInterface<T> is a ValueNotifier<T> with extra listener/stream bookkeeping, so it
interops with anything in Flutter that takes a Listenable/ValueNotifier.
final counter = 1.rx; // Rx<int> via extension
final flag = false.rx; // RxBool
final items = <String>[].rx; // RxList<String>
final model = Rx<Model>(Model()); // explicit
| Member | Behavior |
|---|---|
value setter |
skips notifying when the new value equals the current one |
call([newValue]) |
counter(5) sets, counter() reads — usable directly as a callback |
refresh() |
forces a notify; needed after mutating a field inside the held object |
update((v) => …) |
functional set |
addValueListener / removeValueListener |
typed ValueChanged<T> listeners |
bindStream(stream) / closeStream(stream) |
pipes a stream into the value |
disposed |
true after dispose() |
RxBool adds logical operators (&, |, ^, toggle()); RxList<T> behaves like a
List<T> and notifies on any mutation.
RxWidget<T> is the only widget that listens — keep it as tight around the changing subtree
as possible:
RxWidget<int>(
notifier: state.counter,
builder: (ctx, value) => Text('$value'),
)
Every Rx value must be disposed by whoever created it — occam never disposes one for you.
Example #
example/ is a runnable app (cd example && flutter run). Its lib/main.dart is the
minimal version (CounterPage, in one file); the home screen links to the rest:
| Route | Shows |
|---|---|
/counter |
the whole package in one file: StateWidget, StateController, .rx, RxWidget |
/ |
Rx<int>, Rx<Model> + refresh(), ParentState (also nested), navigation |
/playground |
readyState(), RxBool, call/update, addValueListener, bindStream/closeStream, RxList mutations, disposed, AutomaticKeepAliveClientMixin |
/secondPage |
an RxList<String> rendered as a list |
/bottom |
one StateWidget per tab with PageStorage |
Every demo has a widget test under example/test/.
Quality #
CI runs format, flutter analyze --fatal-infos, the full test suite gated at 100% coverage
(test_cov_console), automatic leak detection on every widget test, a 2,000-instance
mount/unmount soak test, and dart pub publish --dry-run.
See AGENTS.md for the full architecture and the conventions to follow when contributing,
and CHANGELOG.md for version history.
Thanks to: @roipeker.