Next we need work on improving the UI (User Interface) a little bit. We’ll do this by adding images, and removing the debug banner..
Adding Images
Our first step will be to add images to our existing application that we’ve already built.
To do this, I’ve copied the provided images into an assets folder. To prepare them for use, we will open the pubspec.yaml file.
An assets section will need to be added, and links to the images created.
Remember YAML file are case and space sensitive, so be careful editing it.
- assets/d1.png
- assets/d2.png
- assets/d3.png
- assets/d4.png
- assets/d5.png
- assets/d6.png
- assets/dice.jpg
Once you’ve edited the file, you will want to save and close that file.
If you had a preview open, remember that you will probably need to close your app and restart it as hot reload doesn’t always load image assets.
Determining the Image Source
We’re going to update the dice.dart
file so that we use the images instead of the text.
The image source will change based upon what the random value of the dice is going to be. Therefore, we should create a string which will hold the value.
String _image = "assets/d" + _value.toString() + ".png";
Notice that we just concatenate a set of strings, including the _value with the toString() method so we get a complete path.
Of course the issue with this is what happens when the app is initialized and the value is zero? Well, we will need a special case for that. We can reset the image source if _value is zero.
if (_value == 0) {
_image = "assets/dice.jpg";
}
We could have created a d0.png file, but the file type is jpg, and we didn’t want to just change it. That would have required saving it as a different type of file.
Displaying the Image
Next we are going to remove the text field and put the image in it’s place.
So we’ll remove the Text field that is a child of the TextButton. In it’s place we’re going to add the Image.
This is the Image widget. Since this is stored in the application, we will use Image.asset. We’ll set the height and width as well as the source, as we see below.
Image.asset(
_image,
width: 125,
height: 125,
fit: BoxFit.cover,
),
Because _image is the string that is set before hand, it is going to be updated based upon what the value of the new dice roll.
Removing the Debug Banner
Once you have tested your app, you will want to remove the debug banner. This is an easy step.
In the main.dart file, we need to add a single property to the MaterialApp. Under the title, place:
debugShowCheckedModeBanner: false,
At this point, save which should do a hot reload, and you should have the debug banner go away.
Updates to the Dice Game UI was originally found on Access 2 Learn