When we last looked at our ToDo list, we generated a random number.
We’ve finished that task. Onto the next one. This time, we’re going to calculate and show the score. This is going to take a few episodes so hang in there and be patient.
Now, one of the key aspects of learning any new language - whether it be a spoken language or computer language, is repetition. We’ll be doing this a lot in this course to get you used to writing and thinking in Flutter. Our goal is to show you core techniques that you’ll be using all the time in Flutter development.
In this case, we’ll be showing the score. We’re going to modify the Bulls Eye app to show user’s total score at the bottom of the screen. This will be a review of several key things you’ve learned in this course up to this point.
To get started, open your project in progress or download the starter project for this episode. The first thing we’ll do is update the Hit Me button to increment the score.
Open main.dart and scroll down to the Hit Me’s onPressed property. Right now, it’s just showing the dialog. When the dialog appears, we print a message to the console .
We want to inform the widget that we are changing state, so we use the setState method. After the showAlert method, add the following:
setState(() {
});
Then we increase the total score by incrementing the variable by the pointsForCurrentRound method.
_model.totalScore = _model.totalScore + _pointsForCurrentRound();
Notice that we are assigning the total score to itself while adding the result to it. This kind of operation is so common that there is a shorthand operation that makes it easy.
Update it as follows:
_model.totalScore += _pointsForCurrentRound();
The plus equals means we’re just adding to itself. There’s also a minus equals, divide equals and so on. We used multiply equals while calculating the non-negative difference variable in one of the past challenges.
Now before we move on, we have an extraneous print statement in our showAlert method. Let’s delete that now.
Okay, that’s it for main.dart, now we should show our updated Score. Open up score.dart. Replace the string in the text widget to the following:
children: const <Widget>[
Text('Score: '), // old code
Text('$totalScore'),
],
We get a compile error. Mousing over it, you’ll see that the evaluation of a constant expression throws an exception. In plain English, we are assigning a variable which changes inside a constant array which shouldn’t change. To fix this, we remove the const keyword infront of the array and place it on Score text widget.
children: <Widget>[
const Text('Score: '),
Text('$totalScore'),
],
Now on refreshing back the app. Notice we have a score of zero. We’ll move the slider and tap the Hit Me button. The score updates as expected. We’ll move the slider again, and this time, it correctly adds the score. Our game is really coming together.