As mentioned in the beginning of this tutorials series, the official language of Flutter is Dart. It’s make sense to get familiar with Dart in a long term. In general, Dart is a client-optimized language created by Google that is easy to learn. If you got experience of languages like Java, JavaScript, or C++, you will be easier to pick up this language. In other words, Dart powers Flutter by providing a modern, easy-to-read syntax and features designed to build fast and efficient apps.
So, I will try my best to provide a quick overview of Dart fundamentals to get you up. In summary, this tutorial will cover:
- Dart basics: Variables, data types, and control flow.
- Functions and object-oriented programming.
- Collections (lists, maps, sets).
- Asynchronous programming with
async
andawait
.
Let’s begin our Dart journey.
Learn the very basic: Dart Variable
Variables and Data Types
How to declare variables in Dart? You can declare them using either var
, final
, or const
.
The differences between each declaration listed in below table:
var | Declares a variable that can be reassigned |
final | Declares a variable that can only be set once |
const | Declares a compile-time constant |
Let’s see a simple example:
void main() {
var name = 'John'; // Can be reassigned
final age = 25; // Cannot be reassigned
const pi = 3.14; // Compile-time constant
print('Name: $name, Age: $age, Pi: $pi');
}
What kinds of data types Dart supports? Well, most of the common data types are good to go, I have listed down below:
int | For integer values (e.g., 1, 100). |
double | For floating-point values (e.g., 1.5, 3.14). |
String | For text data. |
bool | For boolean values (true or false ). |
Control Flow (If-Else, Loops)
Let’s talk about the control flow. Dart supports standard control flow structures like if-else
, for
, while
, and switch
statements. Below let me just show you few simple examples to demonstrate how to use these logic flow. You should find out it’s quite similar to Java or C# syntax:
Example of if-else in Dart:
void main() {
int score = 85;
if (score >= 90) {
print('Grade: A');
} else if (score >= 80) {
print('Grade: B');
} else {
print('Grade: C');
}
}
Example of for loop in Dart:
void main() {
for (int i = 0; i < 5; i++) {
print('i = $i');
}
}
Example of while loop in Dart:
void main() {
int count = 0;
while (count < 3) {
print('Count is $count');
count++;
}
}
How to create Functions in Dart?
Functions in Dart are first-class citizens, meaning they can be assigned to variables, passed as arguments, or returned from other functions.
Defining Functions
A basic function in Dart:
int add(int a, int b) {
return a + b;
}
void main() {
int sum = add(10, 20);
print('Sum: $sum');
}
- The return type (
int
) is specified before the function name. - Functions can have optional or named parameters for more flexibility.
Optional and Named Parameters
Dart supports optional parameters, allowing you to pass arguments that are not required.
- Positional Optional Parameters: Defined with square brackets.
String greet(String name, [String? message]) {
return 'Hello, $name! ${message ?? ''}';
}
void main() {
print(greet('Alice')); // No message
print(greet('Bob', 'Welcome!')); // With message
}
- Named Parameters: Defined with curly braces.
void displayInfo({required String name, int age = 0}) {
print('Name: $name, Age: $age');
}
void main() {
displayInfo(name: 'John'); // Named parameter usage
}
Object-Oriented Programming in Dart
Dart is an object-oriented language, meaning everything is an object, even functions. Classes are the blueprint for objects.
Defining a Class
class Person {
String name;
int age;
Person(this.name, this.age);
void sayHello() {
print('Hello, my name is $name and I am $age years old.');
}
}
void main() {
Person person = Person('Alice', 30);
person.sayHello();
}
- Constructor: The
Person
class constructor initializesname
andage
. - Method:
sayHello
is a method of the class that prints a greeting.
Inheritance and Polymorphism
Dart supports inheritance, allowing one class to inherit properties and methods from another class.
class Animal {
void makeSound() {
print('Animal makes a sound');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('Dog barks');
}
}
void main() {
Dog dog = Dog();
dog.makeSound(); // Outputs: Dog barks
}
Collections (Lists, Maps, and Sets)
Dart provides powerful collection types: List, Map, and Set.
Lists
A List is an ordered collection of items.
void main() {
List<String> fruits = ['Apple', 'Banana', 'Mango'];
// Add an item
fruits.add('Orange');
// Access item by index
print(fruits[0]); // Outputs: Apple
// Loop through the list
for (var fruit in fruits) {
print(fruit);
}
}
Maps
A Map is a key-value pair collection.
void main() {
Map<String, int> scores = {
'Alice': 90,
'Bob': 85,
'Charlie': 95,
};
// Access value by key
print('Alice\'s score: ${scores['Alice']}');
// Add a new entry
scores['David'] = 88;
// Loop through the map
scores.forEach((key, value) {
print('$key: $value');
});
}
Sets
A Set is an unordered collection of unique items.
void main() {
Set<int> numbers = {1, 2, 3};
// Add an item
numbers.add(4);
// Check if an item exists
print(numbers.contains(2)); // true
}
Asynchronous Programming with async
and await
Dart supports asynchronous programming, making it easy to perform tasks like fetching data from a server without blocking the app’s UI.
Using Future
and async/await
A Future represents a value that will be available at some point in the future.
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2)); // Simulate network delay
return 'Data fetched';
}
void main() async {
print('Fetching data...');
String data = await fetchData();
print(data); // Outputs: Data fetched after 2 seconds
}
- async: Marks a function as asynchronous.
- await: Waits for the result of an asynchronous operation before continuing.
Conclusion: Dart Basics for Beginners
In this quick guide, you’ve learned the essentials of Dart programming, including variables, functions, object-oriented programming, and asynchronous operations. Dart’s clean syntax and powerful features make it an ideal language for building modern mobile apps with Flutter.
With this foundation, you’re ready to dive deeper into Flutter and start building interactive, responsive applications. In the next tutorial, we’ll explore how to integrate backend services like Firebase into your Flutter app using Dart. Keep coding, and happy building!