Here’s a short tutorial to help you get started with Dart:
Installation
To start writing Dart code, you’ll need to download the Dart SDK from the official website: https://dart.dev/get-dart.
Once you have downloaded and installed the Dart SDK, you can create a new project by running the following command in your terminal:
luaCopy codedart create my_project
This will create a new Dart project in a folder called my_project
.
Hello World
Let’s start with a classic “Hello, World!” program. Open up the lib/main.dart
file in your project folder, and replace the contents with the following code:
dartCopy codevoid main() {
print('Hello, World!');
}
This code defines a function called main
, which is the entry point of our program. The print
statement simply prints the text “Hello, World!” to the console.
To run the program, open your terminal and navigate to your project folder. Then, run the following command:
Copy codedart run
This will compile and run your Dart program, and you should see the text “Hello, World!” printed to the console.
Variables
Let’s define a variable in our program. Replace the contents of main.dart
with the following code:
dartCopy codevoid main() {
String name = 'Alice';
int age = 30;
double height = 1.75;
print('My name is $name. I am $age years old and $height meters tall.');
}
In this code, we’ve defined three variables: name
, age
, and height
. We’ve specified the types of each variable (string, integer, and double), and assigned them values.
We’re also using string interpolation to include the variable values in our print
statement.
Functions
Let’s define a simple function in our program. Replace the contents of main.dart
with the following code:
dartCopy codevoid main() {
String name = 'Alice';
int age = 30;
double height = 1.75;
String greeting = getGreeting(name);
print('$greeting I am $age years old and $height meters tall.');
}
String getGreeting(String name) {
return 'Hello, my name is $name.';
}
In this code, we’ve defined a new function called getGreeting
. This function takes a String
parameter called name
, and returns a string containing a greeting.
We’re calling this function in our main
function, and storing the result in a new variable called greeting
. We’re then using string interpolation to include the greeting
variable in our print
statement.
Conclusion
This tutorial has covered some of the basic syntax and features of Dart, including variables, functions, and string interpolation. With this foundation, you can start building more complex Dart applications and exploring the many other features of the language.