ezrohir / snippet

0 stars 0 forks source link

dart-cheatsheet #1

Open ezrohir opened 2 years ago

ezrohir commented 2 years ago

Dart has two kinds of function parameters: positional and named.

class MyColor {
  int red;
  int green;
  int blue;

  MyColor(this.red, this.green, this.blue);
  MyColor({required this.red, required this.green, required this.blue});
}
ezrohir commented 2 years ago

Initializer lists

Sometimes when you implement a constructor, you need to do some setup before the constructor body executes. For example, final fields must have values before the constructor body executes. Do this work in an initializer list, which goes between the constructor’s signature and its body:

NonNegativePoint(this.x, this.y)
    : assert(x >= 0),
      assert(y >= 0) {
  print('I just made a NonNegativePoint: ($x, $y)');
}

class FirstTwoLetters {
  final String letterOne;
  final String letterTwo;

  FirstTwoLetters(String word)
      : assert(word.length >= 2),
        letterOne = word[0],
        letterTwo = word[1];
}