LogoDart Beginner Tutorials

Digital Pets Basic Needs ifelse and Null Safety

This part expands on variable types introduces null safety and uses ifelse statements to handle user input and provide user feedback setting up initial hunger and happiness values for your pet.

Welcome to Part 2! In the previous recipe, we created a simple program that printed a greeting. Now, let's make our digital pet a little more realistic by adding some basic needs: hunger and happiness. We'll also learn about if/else statements and Dart's powerful null safety feature.

Null safety is a crucial concept in Dart that prevents your program from accidentally working with values that haven't been assigned yet (often causing crashes). It ensures that your variables always hold a meaningful value.

Understanding if/else

if/else statements allow your program to make decisions. The code within the if block only runs if a condition is true; otherwise, the code within the else block runs. Let's see this in action:

if (condition) {
  // Code to execute if the condition is true
} else {
  // Code to execute if the condition is false
}

For example:

bool isHungry = true;
if (isHungry) {
  print("The pet is hungry!");
} else {
  print("The pet is not hungry.");
}

Step 1: Adding Hunger and Happiness Variables

Let's add int variables to represent our pet's hunger and happiness levels. We'll use a scale of 0 to 10, where 0 is the lowest and 10 is the highest.

int hunger = 5;
int happiness = 5;

Step 2: Introducing Null Safety and User Input

Now, we'll introduce some null safety. Remember how we got user input earlier? What if the user doesn't enter a name? The stdin.readLineSync() method can return null. To handle this situation, we’ll use a null-aware operator (?.) along with the ?? operator (the null-coalescing operator).

Let's improve our name input:

String? petName = stdin.readLineSync(); // Note the ? for nullable String

petName = petName?.trim() ?? "Buddy"; // If petName is null, it defaults to "Buddy"

The ?. operator only calls .trim() if petName is not null. The ?? operator assigns "Buddy" to petName if it remains null after trimming.

Step 3: Using if/else to Handle User Input

Let's add some feedback based on whether the user provided a name or not.

if (petName == "Buddy") {
  print("No name entered, calling your pet $petName!");
} else {
  print("Hello, $petName!");
}

Step 4: Displaying Initial Status

Let’s print out our pet's initial hunger and happiness levels.

print("Initial hunger level: $hunger");
print("Initial happiness level: $happiness");

That's it for Part 2! We've successfully incorporated if/else statements, managed potential null values, and added our pet's basic needs: hunger and happiness. In Part 3, we'll introduce functions and loops to make our pet even more interactive. We will add functionality for feeding and playing with the pet, and start to use object-oriented programming!