MobX Logo
MobX.dartHassle free state-management for your Dart and Flutter Apps
Edit page
HomeGetting StartedCore Concepts
Examples
ConnectivityCounterCreate the storeConnect the WidgetDiceFormGithub ReposHacker NewsRandom StreamTodos
Guides
Community
API Overview
Developer

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.

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 {
  @observable
  int value = 0;

  @action
  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 StatelessWidget 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.

class CounterExample extends StatelessWidget {
  const CounterExample();

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          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: 20),
                      )),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: counter.increment,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      );
}

See the complete code here.