Great job on completing Part 1! Now, let's make our digital pet even more interactive. In this part, we'll learn how to accept user input to name the pet and store that name, along with other pet attributes, as variables. We'll also introduce different data types in Dart.
Step 1: Introducing int – Tracking Your Pet's Hunger#
Our pet needs food! We'll use an integer variable (int) to represent the pet's hunger level. Add this to your
main.dart
file, below the
petName
variable:
int petHunger = 5; // Initially, the pet is somewhat hungry (scale of 0-10)
We'll use a scale of 0-10, where 0 is not hungry and 10 is starving.
Step 2: Getting User Input with stdin.readLineSync()#
Let's allow the user to choose their pet's name! We'll use
stdin.readLineSync()
to read a line of input from the console. This is the digital equivalent of your pet asking, "What's my name?" Import the
dart:io
library at the top of your file to use
stdin.
import 'dart:io';
Now, modify your
main
function to include the following (replace the existing
petName
assignment):
stdout.write('What would you like to name your pet? '); //Prompt the user
String? petName = stdin.readLineSync(); //Read the user input
if (petName == null || petName.trim().isEmpty) {
petName = 'Buddy';
print('No name entered, calling your pet $petName!');
} else {
petName = petName.trim();
print('Hello, $petName!');
}
stdin.readLineSync()
returns a
String?. The
?
indicates it's a nullable type, meaning it might be
null
(if the user doesn't enter anything). The
if
statement handles this possibility, providing a default name if the user leaves the input blank.
trim()
removes any leading or trailing whitespace from the input.
Step 3: Combining Everything#
Let's put everything together. Here's the complete
main
function after incorporating the changes:
import 'dart:io';
void main() {
stdout.write('What would you like to name your pet? ');
String? petName = stdin.readLineSync();
if (petName == null || petName.trim().isEmpty) {
petName = 'Buddy';
print('No name entered, calling your pet $petName!');
} else {
petName = petName.trim();
print('Hello, $petName!');
}
int petHunger = 5;
print('Your pet, $petName, has a hunger level of $petHunger.');
}
Run your code! Now you can name your digital pet!
What's Next?#
In the next part, "Pet Status Report: Conditional Logic and Output Formatting," we'll use conditional statements (if/else) to create a more dynamic status report for your pet, including hunger and happiness levels, and we'll improve the output format. Get ready for more exciting pet care challenges!
