跳轉到

Features

Variables and Constants

var name = 'Bob';
const PI = 3.14;

Note: Instance variables can be final but not const.

class Point {
  double? x; // Declare instance variable x, initially null.
  double? y; // Declare y, initially null.

  Point(double x, double y) {
    : x = x,
      y = y;
  }
}

final p = Point(1, 2);

The late modifier has two use cases:

  • Declaring a non-nullable variable that’s initialized after its declaration.
  • Lazily initializing a variable.
late String description;

void main() {
  description = 'Feijoada!';
  print(description);
}

Types

List

var my_list = [1, 2, 3];

assert(my_list.length == 3);
assert(my_list[1] == 2);

Set

Set<String> my_set = {};
my_set.add('david');
assert(my_set.length == 1);

Map

Map<String, int> my_map = {
  'a': 23,
  'b': 100,
};

for (var MapEntry(key: key, value: count) in my_map.entries) {
  print('${key} occurred ${count} times');
}

Function

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

// Arrow syntax
int add(int a, int b) => a + b;

Class Modifiers

// Define a pure interface
abstract interface class Flyable {
    void fly();
}

class Bird implements Flyable {

    @override
    void fly() {
        print('I can fly~')
    };
}

Generic

T first<T>(List<T> ts) {
  // Do some initial work or error checking, then...
  T tmp = ts[0];
  // Do some additional checking or processing...
  return tmp;
}

Asynchrony Support

Future<String> lookUpVersion() async => '1.0.0';

void main() async {
  final version = await lookUpVersion();
}

Generator

// Synchronous
Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}

// Asynchronous
Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

Error Handling

try {
    //
} catch (e) {
  print('Error: $e'); // Handle the exception first.
} finally {
    // Then clean up.
}