Hello World in Dart
Your first Dart program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Dart program.
The Code
Create a file named hello.dart:
| |
Clean and simple! Let’s understand what’s happening.
Understanding the Code
void main()- The entry point of every Dart program.voidmeans the function returns nothing.print()- Outputs text to the console with a newline.'Hello, World!'- A string literal. Dart supports both single and double quotes.- Semicolons - Required at the end of statements (like Java, C#, JavaScript).
- Curly braces - Define code blocks.
Running with Docker
The easiest way to run Dart without installing it locally:
| |
Running Locally
If you have the Dart SDK installed:
| |
Expected Output
Hello, World!
Key Concepts
main()is required - Every Dart program must have amain()function- Strong typing - Dart is statically typed, but types can be inferred
- Modern syntax - Familiar to Java, C#, and JavaScript developers
- Fast execution - Dart compiles to efficient native code or JavaScript
Adding Types
Dart has excellent type inference, but you can be explicit:
| |
The String type annotation is optional here - Dart infers it from the assignment.
A More Dart-Like Version
Let’s use some Dart-specific features:
| |
String interpolation with $ is cleaner than concatenation:
$variablefor simple variables${expression}for complex expressions
Functions in Dart
Dart has concise function syntax:
| |
Null Safety Example
Dart’s null safety prevents null reference errors:
| |
A Complete Example with Classes
| |
This demonstrates:
- Classes - Dart is object-oriented
final- Immutable instance variables- Constructor shorthand -
this.greetingautomatically assigns the parameter - Arrow functions - Concise single-expression methods
Dart vs. Other Languages
Java:
| |
JavaScript:
| |
Dart:
| |
Dart strikes a balance - more structured than JavaScript, less verbose than Java.
Next Steps
Continue to Variables and Types to explore Dart’s type system and null safety in depth.