Using this in a constructor
about using this in a constructor
this.propertyName 은 짧고 간단하게 constructor의 values에 값을 할당할 때 사용한다.
class MyColor {
int red;
int green;
int blue;
MyColor(this.red, this.green, this.blue);
}
final color = MyColor(80, 80, 128);
제시된 코드에서 this.은 class 변수에 값을 넣겠다는 것을 의미한다.
이러한 방식은 named parameters에서도 사용된다.
using this in named parameters
class MyColor {
...
MyColor({required this.red, required this.green, required this.blue});
}
final color = MyColor(red: 80, green: 80, blue: 80);
위 코드는 MyColor의 parameters에 this를 사용한 예이다.
여기에는 required가 사용되었는데, int values는 null이 될 수 없기 때문이다.
- 만약, 값을 지정하지 않아도 되는 parameter라면 required를 생략해도 된다.
Question
MyColor([this.red = 0, this.green = 0, this.blue = 0]);
// or
MyColor({this.red = 0, this.green = 0, this.blue = 0});
첫 번째 코드는 리스트?
두 번째 코드는 property names가 parameters가 될 수 있음을 보여주는 예.
Code example
class MyClass {
final int anInt;
final String aString;
final double aDouble;
// Create a constructor here.
}
Solution
class MyClass {
final int anInt;
final String aString;
final double aDouble;
MyClass(this.anInt, this.aString, this.aDouble);
}
참고 사이트: https://dart.dev/codelabs/dart-cheatsheet#initializer-lists
Author And Source
이 문제에 관하여(Using this in a constructor), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kimhr9889/Using-this-in-a-constructor저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)