Dart Basics

Learn the basics of Dart

Dart Basics

Dart is the programming language used in the Flutter framework to develop high-quality, cross-platform mobile, web, and server apps. In this module, we will cover the basics of Dart language.

Variables and Data Types

In Dart, every variable is an object and all objects inherit from the Object class. Dart supports the following basic data types:

int age = 20;
double weight = 58.5;
bool isTrue = true;
String name = "John Doe";
List<int> numbers = [1, 2, 3, 4];
Map<String, int> fruits = {'apple': 1, 'banana': 2};

Control Flow Statements

Control flow statements in Dart include if-else, for loop, while loop, do-while loop, and switch-case statements.

if (age > 18) {
  print('You are an adult.');
} else {
  print('You are not an adult.');
}

for (var i = 0; i < 5; i++) {
  print(i);
}

while (age > 0) {
  age--;
}

do {
  print(age);
} while (age > 0);

switch (fruit) {
  case 'apple':
    print('Apple is healthy');
    break;
  default:
    print('All fruits are healthy');
}

Functions

Functions in Dart are objects and have a type, Function. A function can be assigned to a variable or passed as a parameter to other functions.

void main() {
  print('Hello, World!');
}

int addNumbers(int num1, int num2) {
  return num1 + num2;
}

Exceptions

Exceptions are error events that happen during the execution of the program. Dart provides built-in support for exception handling with try-catch and finally block.

try {
  int result = 12 ~/ 0;
} catch (e) {
  print('An error occurred: $e');
} finally {
  print('This is the finally block');
}

Classes

Dart is an object-oriented language with classes and mixin-based inheritance. Each object is an instance of a class and all classes inherit from Object.

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  void greet() {
    print('Hello, $name');
  }
}

This is a quick overview of Dart basics. To learn more about Dart, consider going through the official Dart documentation.