Skip to main content

Counter

This example is the same as the one in the Getting Started guide. It does add a few details that were missing over there.

info

See the complete code here.

Create the store​

Our Counter store is fairly simple, as seen below. Since we are using annotations, we have:

  • included the part file counter.g.dart. This is generated by build_runner.
  • created the abstract class CounterBase that includes the Store mixin
  • created the class Counter that blends CounterBase with the mixin _$Counter. The mixin is defined in the generated part file.
import 'package:mobx/mobx.dart';

part 'counter.g.dart';

class Counter = CounterBase with _$Counter;

abstract class CounterBase with Store {

int value = 0;


void increment() {
value++;
}
}

The above store defines a single observable value. The action-method increment() is used to increment the value. Using actions gives you a semantic way of invoking mutating operations on the observable state.

Connect the Widget​

Now that our model for the Store is ready, we can focus on bringing it to life with a Widget. Let's create an instance of our store:

final Counter counter = Counter();

Next we create a simple StatefulWidget that renders the count and exposes the Increment button. To make the count automatically update on changes, we wrap the Text widget inside an Observer widget. Any observable that gets used in the builder function of Observer is automatically tracked. When it changes, Observer re-renders by calling the builder again. This can be seen in the highlighted code below.

class CounterExample extends StatefulWidget {
const CounterExample();


CounterExampleState createState() => CounterExampleState();
}

class CounterExampleState extends State<CounterExample> {
final Counter counter = Counter();


Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: const Text('MobX Counter'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Observer(
builder: (_) => Text(
'${counter.value}',
style: const TextStyle(fontSize: 40),
)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: counter.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}

info

See the complete code here.