Chuyển đến nội dung

Bài 3 · Dart essentials

Dart Basics for Flutter

Learn the Dart you need for Flutter: var, final and const, types, string interpolation, operators, control flow, functions, named parameters and arrow syntax.

Flutter code is Dart code, so a little time spent on the language pays off in every later lesson. This chapter covers the parts of Dart you will use constantly. If you know JavaScript, Java, C# or Kotlin, most of it will look familiar; the differences are mostly in the details, such as final versus const and named parameters.

Dart cannot run on this site, so every Dart block is read-only. Where a behavior is easy to imitate, a JavaScript TryIt shows the same idea so that you can experiment. Those stand-ins are JavaScript, not Dart, and we point out where the two differ.

Your first Dart program

Every Dart program starts at a function called main:

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

void means the function returns nothing. Statements end with a semicolon, strings use single or double quotes (single is the common style), and print writes a line to the console.

Variables: var, final and const

Dart is statically typed: every variable has a type known before the program runs. You can write the type yourself or let Dart work it out.

DART
String city = 'Lisbon';   // explicit type
var year = 2026;          // inferred as int
final today = DateTime.now();  // set once, at run time
const maxPlayers = 4;     // fixed at compile time
Keyword Can be reassigned? Value known when?
var Yes Run time
final No (set once) Run time
const No Compile time

A var has its type fixed by the first value, so var year = 2026; year = 'abc'; is an error. Prefer final for anything that does not change; it communicates intent and the analyzer even suggests it. Use const for values known up front, such as sizes and fixed lists. In Flutter, const is also a performance tool: a const widget is built once and reused. You will see why in Widget, Element and RenderObject Trees.

Built-in types

The types you use daily

int and double Whole numbers and decimals. Both are num.
String Text, immutable, UTF-16.
bool Only true or false. No truthy values.
List, Map, Set The collection types.

Dart has no automatic conversion to bool. An if needs a real bool.

1 / 2
DART
int age = 31;
double price = 4.5;
String name = 'Ada';
bool isAdmin = false;

int total = age + 1;
double half = age / 2;     // / always gives a double: 15.5
int whole = age ~/ 2;      // ~/ is integer division: 15

Two details differ from many languages. The / operator always returns a double, and ~/ gives integer division. And a condition must be a real bool: if (age) is a compile error, where JavaScript would accept it.

Strings and interpolation

Put a value inside a string with $name, or ${expression} for anything more than a name:

DART
final user = 'Ada';
final items = 3;
print('Hello, $user!');
print('You have $items items, total ${items * 4.5}.');
print('''
A multi-line string
keeps its line breaks.
''');
print(r'A raw string keeps \n as two characters');

Strings are immutable. Methods such as toUpperCase(), trim(), split(',') and contains('a') return new values. To use a literal dollar sign, write \$.

The next TryIt imitates interpolation with JavaScript template strings, which use a slightly different syntax (${} always, with backticks).

JS Interpolation, as a JavaScript stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Operators worth knowing

Most operators are what you expect: + - * /, == !=, < >, && || !. A few are special:

DART
var a = 7;
a += 2;            // compound assignment
a++;               // increment
var label = a > 5 ? 'big' : 'small';   // ternary
String? input;                          // null for now
var shown = input ?? 'default';         // if-null: use right side when left is null
a ??= 0;                                // assign only if null (a is not null here)
final cascade = StringBuffer()
  ..write('one ')
  ..write('two');                       // cascade: call several things on one object

The cascade (..) is used heavily in Flutter code, for example to configure a controller. The ?? family belongs to null safety, which gets its own lesson: Null Safety.

Control flow

if, for, while, do-while, break and continue work like in C-style languages:

DART
for (var i = 0; i < 3; i++) {
  print('step $i');
}

final names = ['Ada', 'Grace', 'Linus'];
for (final name in names) {
  print(name);
}

var n = 3;
while (n > 0) {
  n--;
}

switch has been modernized. A switch expression returns a value, needs no break and must cover every case:

DART
String describe(int code) => switch (code) {
  200 => 'ok',
  404 => 'not found',
  >= 500 && < 600 => 'server error',
  _ => 'something else',
};

The underscore is the default case. The >= 500 && < 600 form is a pattern, a feature you will meet again in Collections and Generics.

Functions

A function states its return type, name and parameters:

DART
int add(int a, int b) {
  return a + b;
}

// One expression? Use arrow syntax.
int double_(int x) => x * 2;

The arrow => expression is shorthand for { return expression; }. It works only for a single expression, not a block of statements.

Optional, named and required parameters

Flutter relies on named parameters everywhere, which is why widget code reads like labels:

DART
String greet(String name, {String greeting = 'Hello', bool shout = false}) {
  final text = '$greeting, $name';
  return shout ? text.toUpperCase() : text;
}

String log(String message, [String level = 'info']) => '[$level] $message';

void main() {
  print(greet('Ada'));                           // Hello, Ada
  print(greet('Ada', greeting: 'Hi', shout: true));
  print(log('started'));                         // positional optional
}
  • Parameters in { } are named. Callers write shout: true, and the order does not matter.
  • Named parameters are optional unless marked required: {required String title}.
  • Parameters in [ ] are optional positional parameters.

Functions are values too. You can store them in variables and pass them around, which is how callbacks like onPressed work:

DART
final shout = (String s) => s.toUpperCase();
final names = ['ada', 'grace'].map(shout).toList();

JavaScript has no named parameters, but an object argument behaves in a similar way. This TryIt shows the idea:

JS Named parameters, imitated with an options object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the difference between final and const?

    Both prevent reassignment. A const value must be a compile-time constant, which also lets Flutter reuse const widgets.
  2. 2. What does 7 / 2 return in Dart?

    The / operator always returns a double. Use ~/ for integer division, which gives 3.
  3. 3. Which is a valid way to call greet('Ada', shout: true) when shout is declared inside { }?

    Parameters inside braces are named. Callers pass them as name: value, and order does not matter.
  4. 4. What is true about arrow syntax (=>)?

    => expression means { return expression; }. For several statements, use a block body.

Summary

  • Use final by default, const for compile-time values, and var when the type is obvious.
  • int, double, String and bool are the basics; / returns a double and ~/ divides integers.
  • Interpolate with $name or ${expression}.
  • Switch expressions return values and need no break.
  • Named parameters (in { }) and required make Flutter code readable; => shortens one-expression functions.
  • Dart blocks are read-only here; the TryIts are JavaScript stand-ins.

Next: Null Safety

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.