We’ve seen how to get roll the dice from the main widget with a button by using the GlobalKey in our previous notes. But what if we want to update the score if a single dice is clicked…I mean rolled?
Well that requires talking to the parent widget to let us know that it has changed. There are a couple of ways of doing this, first through Event Listeners which we’ve previously seen, or through callback functions. In this example we’re going to use a callback function.
A callback function is a function which we pass to object, so that the object can call it when it needs to. This can be in the form of either an anonymous function or a named function, and we’ve already seen them we using things like the onPress events.
Our Existing Function
We already have a function to calculate the score of both Dice. So this is the function we’re going to pass as our callback function.
Just as a reminder, I’m putting the function below.
void _calcScore() {
int? l = (_leftKey.currentState?.getValue());
int? r = (_rightKey.currentState?.getValue());
setState(() {
_totalScore = l! + r!;
});
}
Passing a Function to Use as a Callback
We’re going to pass a function by passing it to the constructor of the Dice class. That way the Dice objects will have access to the function.
Now, within the main.dart file, when we create our left and right dice, we should see:
var _left = new Dice(key: _leftKey, parentAction: _calcScore);
var _right = new Dice(key: _rightKey, parentAction: _calcScore);
Notice we have provided an additional argument to pass to the constructor, so we will need to modify our class to handle this.
Updating the Dice Class
In our dice.dart file, we will go to the Dice class and add a variable to hold the function. The function in Dart is treated like an object internally, which is why we can store it in a variable.
However, we need to use a special type of variable so Dart knows that it is a function:
final VoidCallback parentAction;
This is placed inside the Dice class as an instance variable.
Next we will update the constructor to accept the new parameter.
const Dice({Key? key, required this.parentAction}) : super(key: key);
Since the parentAction is final, we need to set it at the constructor by using the required keyword.
Calling our Parent’s Function
Now all we have to do is call the function. We will do this when we roll. We cannot just call parentAction, instead we need to insert this line.
// calling the callback function found in the parent
widget.parentAction();
This is inside of our roll object. When we press on an individual dice, it will update the value, then the parent will get the notification that it needs to recalculate the score, getting us the total score update.
Setting Score if a Single Dice is Pressed was originally found on Access 2 Learn
One Comment
Comments are closed.