Counter
How to write a Hello World Flutter application with UtopiaHooks.
To visit Counter repository press HERE.
Simplified Project Structureβ
|- counter_page.dart - Coordinator between state & view layers
|- state
| |- counter_page_state.dart - Layer that definies State and Hook responsible for business-logic
|- view
|- counter_page_view.dart - View layer
For more info about our recommended directory structure visit our Guide.
CounterPageState πβ
counter_page_state.dart
consists of two segments: CounterPageState
object and useCounterPageState
Hook responsible
for state management. They can be separated to two independent files to achieve "cleaner" directory structure, but
usually they are kept together for programming convenience.
CounterPageState
contains everything necessary for View
, including variables and functions.
useCounterPageState
serves as a wrapper for all the necessary hooks for CounterPage
's business-logic. In this simple
usecase
useState is enough.
class CounterPageState {
final int value;
final void Function() onPressed;
const CounterPageState({required this.value, required this.onPressed});
}
CounterPageState useCounterPageState() {
// simple int state for incrementation
final state = useState<int>(0);
return CounterPageState(
value: state.value,
// state mutation
onPressed: () => state.value++,
);
}
CounterPage - Coordinator πβ
We start with a simple wrapper that serves as a bridge between our state and view. In this simple case it's only
responsible
for initializing CounterPageState
.
In more complex structures, it also provides Flutter-related functions, such
as Navigator.of(context).push
to useCounterPageState
Hook.
class CounterPage extends StatelessWidget {
const CounterPage();
Widget build(BuildContext context) => const HookCoordinator(use: useCounterPageState, builder: CounterPageView.new);
}
CounterPageView πβ
CounterPageView is responsible for displaying the current count and a button that increments the value. It uses
the CounterPageState
passed by CounterPage
.
class CounterPageView extends StatelessWidget {
final CounterPageState state;
const CounterPageView(this.state);
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text("Flutter demo counter page"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
Text(
// current value
'${state.value}',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
// incrementation
onPressed: state.onPressed,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Crafted specially for you by UtopiaSoftware π½