fst 0.2.5 fst: ^0.2.5 copied to clipboard
State tree interface implementation for Flutter + Flutter specific APIs
import 'package:flutter/material.dart';
import 'package:fst/fst.dart';
void main() {
runApp(const CounterApp());
}
class CounterApp extends StatelessWidget {
const CounterApp({super.key});
Widget counter(BuildContext context, StateTreeNode n, Widget child) {
final (count, setCount) = n.state(0);
n.action((context, Increment intent) {
final newCount = count + intent.delta;
setCount(newCount);
return newCount;
});
n.provide(count);
return child;
}
Widget deltaModifier(BuildContext context, StateTreeNode n, Widget child) {
final (incrementBy10, setIncrementBy10) = n.state(false);
final focusNode = n.create(() => FocusNode());
n.provide(incrementBy10);
return RawKeyboardListener(
focusNode: focusNode,
autofocus: true,
onKey: (event) {
if (event.isShiftPressed) {
setIncrementBy10(true);
} else {
setIncrementBy10(false);
}
},
child: child,
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: StateTreeBuilder(
counter,
child: StateTreeBuilder(
deltaModifier,
child: const Home(),
),
),
);
}
}
class Increment extends Intent {
final int delta;
const Increment(this.delta);
}
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('State Tree Example'),
),
body: Center(
child: StateTreeBuilder((context, n, _) {
final count = n.consume<int>();
return Text('Count: $count');
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
final incrementBy10 = context.read<bool>();
final delta = incrementBy10 ? 10 : 1;
Actions.invoke(context, Increment(delta));
},
child: const Icon(Icons.add),
),
);
}
}