Counter example
A very simple example with a counter.
See the code here.
In this example we've used a StatefulWidget
because we must not forget to dispose()
the created signal.
We've used counter
as our signal name:
final counter = Signal(0);
Starting it from the 0
value.
In the dispose()
method we dispose the signal:
@override
void dispose() {
counter.dispose();
super.dispose();
}
To display the counter
value we've used a SignalBuilder
that rebuild any time the counter
value changes:
SignalBuilder(
signal: counter,
builder: (_, value, __) {
return Text('$value');
},
)
And finally to update our counter
value we've used a FloatingActionButton
:
FloatingActionButton(
onPressed: () {
counter.value++;
},
child: const Icon(Icons.add),
)
Testing
Testing the counter is pretty simple
testWidgets('Counter increments', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});