Basic Syntax in Dart
Dart is a robust programming language that balances simplicity and power, which makes it an excellent choice for both beginners and experienced developers. In this article, we'll dive into the fundamental syntax elements of Dart, including variables, data types, and operators. Understanding these building blocks is essential for writing efficient and effective Dart code.
Variables in Dart
Variables in Dart are used to store data that can be referenced and manipulated throughout your program. Dart is a strongly typed language, which means that each variable has a specific type that determines what kind of data it can hold.
Declaring Variables
You can declare a variable using the var keyword, or you can specify its type explicitly. Here’s how you can declare variables:
var name = 'John Doe'; // Using var
int age = 30; // Explicitly declaring an integer
double height = 5.9; // Explicitly declaring a double
bool isStudent = true; // Explicitly declaring a boolean
Using var allows the Dart compiler to infer the variable type from the assigned value, making code concise. However, when you explicitly define a type, it can improve code readability.
Constants
If you want to declare a variable that cannot change once set, you can use the final or const keywords:
final currentDate = DateTime.now(); // This can only be set once
const pi = 3.14; // Compile-time constant
Both final and const ensure that the value cannot be reassigned, with const providing compile-time values while final allows values to be set at runtime.
Data Types in Dart
Dart supports several built-in data types. Here are some of the most common ones:
1. Numeric Types
Dart has two main numeric types: int and double.
- int: Whole numbers without a decimal point.
- double: Numbers that can contain decimal points.
int count = 15;
double temperature = 37.5;
2. Strings
Strings in Dart are enclosed in either single or double quotes.
String greeting = 'Hello, Dart!';
String anotherGreeting = "Welcome to the Dart tutorial.";
Dart also supports multi-line strings using triple quotes:
String multiLine = '''
This is a multi-line string.
You can write across multiple lines.
''';
3. Booleans
The boolean type represents truth values, true or false.
bool isOnline = true;
bool hasPermission = false;
4. Lists
Lists are ordered collections of objects and can be declared using the List keyword.
List<String> colors = ['Red', 'Green', 'Blue'];
List<int> numbers = [1, 2, 3, 4, 5];
You can also create lists using the literal syntax:
var fruits = ['Apple', 'Banana', 'Orange']; // Type inferred as List<String>
5. Maps
Maps are key-value pairs, ideal for storing related data. A Map can be created using the Map keyword.
Map<String, int> ages = {
'John': 30,
'Doe': 24,
'Alice': 28,
};
6. Sets
Sets are collections of unique items. A Set can be created using the Set keyword.
Set<String> uniqueItems = {'item1', 'item2', 'item3'};
Operators in Dart
Operators in Dart are symbols that perform operations on variables and values. Dart supports various types of operators, including arithmetic, relational, and logical operators.
1. Arithmetic Operators
Dart includes standard arithmetic operators:
- Addition (
+) - Subtraction (
-) - Multiplication (
*) - Division (
/) - Modulus (
%)
Here is a simple example:
int a = 10;
int b = 3;
var sum = a + b; // 13
var difference = a - b; // 7
var product = a * b; // 30
var quotient = a / b; // 3.333...
var modulus = a % b; // 1
2. Relational Operators
These operators are used to compare two values and return a boolean result.
- Equal to (
==) - Not equal to (
!=) - Greater than (
>) - Less than (
<) - Greater than or equal to (
>=) - Less than or equal to (
<=)
Example:
int x = 5;
int y = 10;
bool isEqual = x == y; // false
bool isNotEqual = x != y; // true
bool isGreater = x > y; // false
3. Logical Operators
Logical operators are used for combining boolean expressions.
- AND (
&&) - OR (
||) - NOT (
!)
Example:
bool condition1 = true;
bool condition2 = false;
bool resultAnd = condition1 && condition2; // false
bool resultOr = condition1 || condition2; // true
bool resultNot = !condition1; // false
Control Flow Statements
Understanding control flow statements is crucial for writing effective Dart code. Dart provides various control flow constructs, including if, else, for, while, and switch.
If Statement
You can use the if statement to execute code based on a condition.
if (age >= 18) {
print('You are an adult.');
} else {
print('You are a minor.');
}
For Loop
The for loop is used to iterate a set number of times.
for (var i = 0; i < 5; i++) {
print('Iteration $i');
}
While Loop
A while loop continues as long as a condition is true.
var count = 1;
while (count <= 5) {
print('Count is $count');
count++;
}
Switch Statement
The switch statement allows you to execute different code blocks based on the value of an expression.
var fruit = 'Apple';
switch (fruit) {
case 'Apple':
print('You selected an apple.');
break;
case 'Banana':
print('You selected a banana.');
break;
default:
print('Unknown fruit selected.');
}
Conclusion
Understanding basic syntax in Dart is the first step to writing powerful applications with this versatile programming language. By mastering variables, data types, and operators, along with control flow statements, you build a solid foundation to enhance your skills further. Dart's syntax is designed to be clear and expressive, making it easier for you to share your creativity through code. So, get started, practice writing code, and embrace the world of Dart programming!