LogoDart Beginner Tutorials

Part 1: The Hatching! – Your First Digital Pet Program#

Welcome, aspiring digital pet parent! You've just received your very own digital pet egg, and it's ready to hatch! But before the adorable creature pops into existence, we need to write a little bit of code to bring it to life. Don't worry, it's easier than you think. We'll start by building the basic structure of our program and giving your pet a name. This will introduce you to some fundamental concepts in Dart, the programming language we'll be using.

First, let's create the foundation of our program. Every Dart program starts with a main function. Think of this as the entry point—where everything begins. Let's create it:

void main() {
  // We'll add our code here later!
}

This simple line defines a function called main that doesn't return any value (void). All the magic will happen inside the curly braces {}.

Now, let's get to know our pet. The first thing we'll do is give it a name. We'll use the stdin.readLineSync() function to get input from the user (that's you!), and store it in a variable. A variable is like a container that holds information. In this case, it will hold the pet's name which will be a String (text). Because the user might not enter a name, we'll use a String? which allows for the possibility of null (no value). Let's add this to our main function:

void main() {
  stdout.write('What would you like to name your pet? ');
  String? petName = stdin.readLineSync(); 
}

We're using stdout.write to display a message asking for the pet's name. Then stdin.readLineSync() waits for the user to type something and press Enter. The typed text is then stored in the petName variable.

But what if the user doesn't enter a name and just hits Enter? We need to handle that case to avoid errors! Let's add some error handling using an if/else statement and the trim() method (to remove any extra spaces):

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!');
  }
}

This code checks if petName is null or empty after removing leading/trailing spaces. If so, it assigns the default name "Buddy." Otherwise, it prints a greeting using the entered name. Notice how we use $petName to embed the variable's value directly into the string – this is called string interpolation and makes your code more readable.

Now run this code! You've created your first interactive program, and your digital pet has a name.

Our little digital egg is ready to fully hatch! In the next part, "Feeding Time!", we'll introduce functions and data types so we can feed our hungry new friend. Get ready for more fun and coding!