Leave a rating/review
Now we need to a slider to our game.
For this, we’ll use the Slider widget. The Slider widget lets a user enter a number by sliding a control (which is called a thumb) along a straight-line track where one end represents a minimum value and the other end represents a maximum value.
I want to point out that in most apps, you wouldn’t make the user enter a precise number value like this using a slider, because that can be kind of frustrating. However, for a game like Bullseye, the slider makes the game challenging, which is a good thing. After all, we don’t want to make it too easy for the player!
When creating a slider, you have a bunch of options.
First, a min and max values so if you wanted to make a slider between one and five, you’d set the min to one and the max to five.
You provide a variable that stores the value for the slider in the value field.
You can also respond to changes in the onChanged property. You can also assign certain divisions as well.
We’ll get started creating a simple slider, but in the follow-up course, we’ll customize it.
To get started, open the project in progress or download the starter project for this episode. Instead of just adding a slider to our interface, we’ll encapsulate it in a widget. First, create a new file named control.dart.
Make sure to import the material library.
import 'package:flutter/material.dart';
Now, we’ll add a Stateful Widget since we want to remember the state of the slider. Type ST and select the Stateful Widget option. Give it the name: Control.
Now, we need to create a variable to remember the slider state. We’ll call it currentValue. We’ll make it a private variable. Remember, by using an underscore we are stating that we only want this class to use the variable.
Add the following to _ControlState:
var _currentValue = 50.0;
We’re getting a warning letting us know that we aren’t using the variable. We can ignore for now. Now, to the Build method. Have it return a Row widget
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
],
);
Now, we’ll add some children. We’ll add a label for the minimum value, a slider, and a text label for the maximum value.
const Text('1'),
Slider(
value: _currentValue,
onChanged: (newValue) {},
min: 1.0,
max: 100.0,
),
const Text('100')
Now we want to set the new value of the currentValue property in onChanged. We do this by calling the method setState. We’ll cover this method later in this course.
setState(() {
_currentValue = newValue;
print(_currentValue);
});
And that’s it. We are all good to go. It’s time to implement our new slider. Open main.dart. First, import control.dart.
import 'control.dart';
Now in _GamePageStateState, put our new control widget underneath the prompt widget.
const Prompt(targetValue: 100),
const Control(),
Now build and run your app or hot reload. You’ll see that we now have a slider. It’s looking good!