Dice
In this example, we will build a fun dice app. You can make the dice roll at the tap of a button and a random count is generated with every roll of dice.
See the complete code here.

Store setup
The DiceCounter store is quite simple. It keeps a track of dice values and the total count. Below is how it looks:
- Generate
dice_counter.g.dartfile usingbuild_runnerand this must be imported into the store. Read more aboutbuild_runnerin the MobX Code Generation library,.
- In the above store
leftandrightare the dice counts defined with@observableannotations and are initialised with a random number ranging from 1 - 6. totalis also an observable which keeps track of the total count of the dice.- The action-method
roll()defined with@actionannotation is used to update the dice counts every time user taps on the dice.
With the above implementation I was able to keep a track of the left, right and total counts with every user interaction as expected or so I thought ๐ค.
Discovering
@computedI ran into an issue... The
totalcount wasnullfor the very first time. It gets updated only when the action-methodroll()is called. In search of the solution I went through the documentation and few examples and realised there is an insanely easy way to get around this issue.@computedBOOM! my issue is solved.
I have modified the above DiceCounter implementation using @computed.
- Now
totalis a computed observable annotated with@computed. Computed observables are in-sync every time left or right count is updated. - The value of
totalis automatically updated when the instance of the store is created so I no longer have thenullvalue when I load the app. @computeddoes more than that. Now, I do not have to write any additional code like the above in the action-method to update it.
It exactly does what the author of mobx quoted... "What can be derived, should be derived. Automatically".
Integrating the Store with the View
Now that the DiceCounter store is ready, it's time to add it to the Widget to see the magic happen. Let's create an instance of our store:
The observables and actions from the store can be accessed via the newly created instance diceCounter along with the Observer widget as shown below:
Summary
The working example will be as seen in the figure below:

See the complete code here.