Delve into the foundational concepts of Dart programming with this comprehensive guide. Covering essential topics like syntax, variable types, functions, loops, and control flow, the article offers a thorough understanding of Dart basics. Ideal for beginners, it lays the groundwork for mastering Dart, from simple data types to complex functions, ensuring a strong foundation in this versatile and powerful programming language.
Welcome to the world of Dart, a modern language designed for ease of use and high performance. Whether you're aiming to develop mobile apps with Flutter or looking to explore web and server-side development, learning Dart is your first step. In this article, we'll dive into the basic syntax and fundamental concepts of Dart, setting a strong foundation for your coding journey.
Basic Syntax
Hello World in Dart
Every programming journey often begins with a 'Hello World' program. Here's what it looks like in Dart:
void main() {
print('Hello, World!');
}
This program defines a main function, which is the entry point of every Dart application. The print function outputs the string 'Hello, World!' to the console.
Variables and Data Types
Basic Declaration and Initialization
In Dart, variables can be declared using either explicit type annotations or the var keyword for type inference.
Type Annotation:
String name = 'Alice';
int age = 30;
Type Inference with var:
var city = 'New York'; // Inferred as String
var distance = 100; // Inferred as int
Final, Const, and Late
Dart provides final, const, and late keywords for special variable declarations.
final: For values that are set once and are immutable.
final String greeting = 'Hello';
const: Declares compile-time constants.
const double pi = 3.14159;
๐ก
In dart there is no convention of using UPPERCASE letters when using constant variable. Instead dart uses k letter at the beginning of variable name. ex: kAnimationDuration = Default Animation Duration in Flutter
ย
late: Indicates delayed initialization.
late String description; // can be reassigned
late final int calculatedValue; // once set vaue
late String? nullOrStringValue; // must be either null or String value.
๐ง
Using late keyword is risky, if variable does not assigned(even itโs nullable - String?) and being used, dart throws compile-time error.
ย
Code examples
late String description;
late String? nullableDescription;
late dynamic dynamicValue;
late var lateVariable;
late final String finalVariable;
late final String? nullableFinalVariable;
///! Error late variable must be initialized before use
// print(description);
// print(nullableDescription);
description = 'Hello';
print(description); //* OK => prints Hello
nullableDescription = null;
print(nullableDescription); //* OK => prints null
nullableDescription = 'Hello';
print(nullableDescription); //* OK => prints Hello
dynamicValue = 'Hello';
print(dynamicValue); //* OK => prints Hello
dynamicValue = 1;
print(dynamicValue); //* OK => prints 1
dynamicValue = null;
print(dynamicValue); //* OK => prints null
lateVariable = 'Hello';
print(lateVariable); //* OK => prints Hello
lateVariable = 2; //* OK
print(lateVariable); //* OK => prints 2
finalVariable = 'Hello';
print(finalVariable); //* OK => prints Hello
// finalVariable = 2; //! Error => The final variable 'finalVariable' can only be set once.
nullableFinalVariable = null;
print(nullableFinalVariable); //* OK => prints null
// nullableFinalVariable = 'Hello'; //! Error => The final variable 'nullableFinalVariable' can only be set once.
Dynamic vs Var
Dart offers two dynamic types: dynamic and var. The difference lies in type checking:
dynamic: Explicitly disables static type checking. The type can change over time.
Set<int> numbers= {1, 2, 3, 4, 5};
var numbers2 = {1, 2, 3, 4, 5}; // Inferred as Set<int>
๐ก
Dart also supports popular collection types like: Queue, Stack, LinkedList, Tuple etc
Runes and Symbols
Runes: For representing Unicode characters in Dart.
Runes input = new Runes('\u{1F605}');
print(new String.fromCharCodes(input)); // ๐
Symbols: Represent operators or identifiers used in Dartโs reflection capabilities.
Null Safety
Dart 2.12 introduced null safety, making all variables non-nullable by default.
Nullable types with ?:
int? nullableAge;
Null-aware operators (?., ??, ??=):
int? age;
print(age?.isEven); // Use ?. for safe access
// same as
if(age != null) {
print(age.isEven) // prints boolean value
} else {
print(age) // prints null
}
print(age ?? 0); // Default value if null
// same as
if(age != null) {
print(age); // age value
} else {
print(0);
}
age ??= 10; // Assign value if null
// same as
if(age !=null) {}
else {
age = 10;
}
ย
Loops in Dart.
For Loop
Standard For Loop: Iterates a set number of times.
for (int i = 0; i < 10; i++) {
print('Iteration $i'); // prints 0 ~ 9
}
For-In Loop: Iterates over elements in a collection.
var numbers = [1, 2, 3, 4, 5]; // Inferred as List<int>
for (var number in numbers) {
print('Number: $number');
}
While Loop
Executes as long as the condition is true.
int count = 0;
while (count < 5) {
print('Count is $count');
count++;
}
// prints 0 ~ 4
Do-While Loop
Executes the block once before checking the condition.
int counter = 0;
do {
print('Counter is $counter');
counter++;
} while (counter < 5);
Break and Continue
Break: Exits the loop immediately.
for (int i = 0; i < 10; i++) {
if (i == 5) break; // Exits the loop when i is 5
print(i);
}
Continue: Skips the rest of the current loop iteration.
dartCopy code
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // Skips even numbers
print('Odd: $i');
}
Logical Blocks
Simple If Statement
Executes code block if the condition is true.
int age = 20;
if (age >= 18) {
print('Adult');
}
If-Else Statement
Provides an alternative path if the if condition is false.
Allows adding new functionalities to existing classes.
extension StringExtension on String {
bool get isCapitalized =>
this.length > 0
&&
this[0].toUpperCase() == this[0];
}
Function Parameters and Default Values
Default Parameter Values
Set default values for parameters, both positional and named.
void printMessage(String message, {int times = 1}) {
for (int i = 0; i < times; i++) {
print(message);
}
}
Required Named Parameters
Making a named parameter required using required keyword.
void setAddress({required String street, String? city}) {
// Function body
}
Conclusion
This overview introduces you to the very basics of Dart programming. You've seen how to write a simple Dart program, declare variables, use control flow statements, define functions, and handle errors. As you progress, these concepts will be the building blocks for more complex and exciting Dart applications.
Stay tuned for our next article where we delve deeper into the world of Dart!
Flutter does not have native 3D rendering support out-of-the-box, but it can be extended to render 3D graphics using external libraries and plugins. To build a Three.js-like 3D library for Flutter, we need to consider existing solutions, rendering technologies (WebGL, Vulkan, OpenGL), language interoperability, performance, and cross-platform challenges. Below is a structured overview of how such a library can be implemented, including current tools, best practices, and recommendations.