02. Dart의 문법 Ninja Language Cheatsheet - pksung1/learn_flutter GitHub Wiki

빠르게보기 위한 정리

String 표현식

'${3 + 2}' // -> '5'
'${"word".toUpperCase()}' // -> 'WORD'
'$myObject' // -> call myObject.toString()

Nullable variables

널을 저장할수 있는 변수

int? a = null

Null aware operators

널 처리 연산자

int? a; // null
a ??= 3 // a가 null이라면 대입
print(a) // 3

a ??= 5
print(a) // 3

print (1 ?? 3) // 1
print (null ?? 3) // 3

Conditional property access

myObject?.someProperty?.someMethod() 

Collection iterals

final aListOfStrings = ['a', 'b', 'c']; // 배열
final aSetOfStrings = {'one', 'two', 'three'}; // 집합
final aMapOfStringsToInts = {
  'one': 1,
  'two': 2,
  'three': 3
};

final aListOfInts = <int>[];
final aMapOfIntToDouble = <int, double>{};

Array Syntex

bool hasEmpty = aListOfStrings.any((s) {
  return s.isEmpty;
});

Cascades

.. 연산자로 실행할수 있음. kotlin의 with같은 역할을 한다.

querySelector('#confirm')
  ?..text = 'Confirm'
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'))
  ..scrollIntoView();

Getter and Setter

class MyClass {
  int _aProperty = 0;

  int get aProperty => _aProperty;

  set aProperty(int value) {
    if (value >= 0) {
      _aProperty = value;
    }
  }
}

Optional Postion parametes

int sumUpToFive(int a, [int? b, int? c, int? d, int? e]) {
  int sum = a;
  if (b != null) sum += b;
  if (c != null) sum += c;
  if (d != null) sum += d;
  if (e != null) sum += e;
  return sum;
}
// ···
  int total = sumUpToFive(1, 2);
  int otherTotal = sumUpToFive(1, 2, 3, 4, 5);


// 또는 아래와같이 null일때 기본값을 할당할수도 있음
// int sumUpToFive(int a, [int b = 2, int c = 3, int d = 4, int e = 5]) { ... }

Named Parameters

void printName(String firstName, String lastName, {String? middleName}) {
  print('$firstName ${middleName ?? ''} $lastName');
}
// ···
printName('John', 'Smith', middleName: 'Who');

// 중괄호로 감싼 파라미터는 네임드 파라미터를 활용할수 있다. 이 또한 기본값 할당이 가능하다.
// void printName(String firstName, String lastName, {String middleName = ''}) { ... }

Exceptions

try, on, catch, rethrow, throw, finally 등 기본 예약어들이 있다.

try - 보통 아는 try on - 에러타입을 작성한다. catch - throw된 에러객체를 받을수있다. rethrow - catch 안에서 동일한 에러를 계속 발생시키고 싶다면 rethrow; 를 단독실행한다. finally - try, catch문 마지막에 작성한다.

this

클래스의 this문법과 동일함

initializer lists (생성자 초기 처리)

assert문을 넣어 검증하기 좋은 구간임

class FirstTwoLetters {
  final String letterOne;
  final String letterTwo;

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

Named constructor

빠르게 새로운 객체를 생성할때 사용된다.

class Point {
  double x, y;

  Point(this.x, this.y);

  Point.origin()
      : x = 0,
        y = 0;
}

// Point.origin() -> Point(x: 0, y: 0)

Factory constructors

Dart는 팩토리 생성자를 지원합니다.

class Square extends Shape {}

class Circle extends Shape {}

class Shape {
  Shape();

  factory Shape.fromTypeName(String typeName) {
    if (typeName == 'square') return Square();
    if (typeName == 'circle') return Circle();

    throw ArgumentError('Unrecognized $typeName');
  }
}

// Shape.fromTypeName('square') -> Square()

Redirecting constructors

this를 활용해 새로운 객체를 생성할수 있음. 대신 델리게이트이기 때문에 앞에 클래스명.함수명 으로 작성해주어야함

class Automobile {
  String make;
  String model;
  int mpg;

  // The main constructor for this class.
  Automobile(this.make, this.model, this.mpg);

  // Delegates to the main constructor.
  Automobile.hybrid(String make, String model) : this(make, model, 60);

  // Delegates to a named constructor
  Automobile.fancyHybrid() : this.hybrid('Futurecar', 'Mark 2');
}

Const constructors

절대 변경되지 않는 객체를 생성할때는, 컴파일 타임 상수로 만들수 있습니다.

class ImmutablePoint {
  static const ImmutablePoint origin = ImmutablePoint(0, 0);

  final int x;
  final int y;

  const ImmutablePoint(this.x, this.y);
}
⚠️ **GitHub.com Fallback** ⚠️