dart (flutter) 문법 - 생성자.

플러터는 생성자의 구문이 매우 다양 합니다.

https://dartpad.dev 에 아래 코드를 복사해서 실행해 보세요.

factory 는 다음 페이지에 정리되어 있습니다.

class Animal {
String name = '';
int id = 0;

// 이름 없는 생성자.
Animal() {}

// 이름 없는 생성자는 하나이상 만들수 없다.
// Animal(int i) { } // 에러.

// 이름 있는 생성자.
Animal.name() {}

// 생성자를 여러개 만들수 있고
// 멤버변수의 기본값을 설정할 수 있다.
Animal.nameNew() : name = 'test' {}

// 생성자에서 파라메터를 받을수 있다.
// 아래 생성자는 동일한 동작을 한다.
Animal.arg(String n) {
name = n;
}

Animal.arg2(String n) : name = n {}

Animal.arg3(this.name);

// {} 로 둘러산 부분은 호출시에 이름을 지명해야 한다.
// ) Animal a = Animal.argName(name:'go', id:2);
Animal.argName({required this.name, required this.id});

// [] 로 둘러싼 부분은 호출시에 값이 없으면 기본값을 지정한다.
// )
// Animal a = Animal.argName2();
// Animal a2 = Animal.argName2('go');
// Animal a3 = Animal.argName2('go'. 33);
// Animal a4 = Animal.argName2(33); // 이건 에러.
Animal.argName2([this.name = 'hi', this.id = 1]);

// 플러터에서 아래 문법은 지원하지 않는다.
//Animal.error(n, this.id) : this.arg(n);
//Animal.error2(String n, int i) : this.arg(n) { id = i; }
}

class Cat extends Animal {
// super 키워드로 부모 클래스의 멤버변수에 접근할 수 있다.
Cat.par() {
super.name = 'cat';
super.id = 2;
}

// 부모 클래스의 생성자에 접근할 수 있다.
Cat.par2() : super.argName(name: 'cat', id: 2);
}

class ConstTest {
// const생성자를 만들기 위해서는
// 멤버변수가 final 로 선언되야 한다.
final String name;

// const 생성자는 변하지 않는 클래스를 만든다.
// flutter 위젯 빌드시 성능 향상을 위해 많이 사용한다.
const ConstTest(this.name);
}

// final 변수는 클래스 인스턴스화 시에 반드시 값을 할당해야 한다.
// 이로인해 생성자 구현시 여러 제한 사항이 생긴다.
// 예로 들어 아래 구문들이 가능하다.
class FinalTestBase {
final int a;

FinalTestBase(this.a);

FinalTestBase.init(this.a);
}

class FinalTest extends FinalTestBase {
final int b;

FinalTest.test(super.a, this.b);

FinalTest.test2({required a, required this.b}) : super(a);

FinalTest.test3([super.a = 1, this.b = 2]);

FinalTest.test4(argA, this.b) : super(argA);

FinalTest.test5(argA, this.b) : super.init(argA);
}

void main() {
// 생성시에도 const 를 달아줘야 const로 생성된다.
// 동일한 파라메터로 const 생성된 인스턴스는 동일하다.
ConstTest d = const ConstTest('hi');
ConstTest d2 = const ConstTest('hi');
print(identical(d, d2)); // true

ConstTest d3 = ConstTest('hi');
ConstTest d4 = ConstTest('hi');
print(identical(d3, d4)); // false

const ConstTest d5 = ConstTest('hi');
const ConstTest d6 = ConstTest('hi');
print(identical(d5, d6)); // true

print(identical(d, d6)); // true

// 파라메터가 다르면 const 생성된 인스턴스는 다르다.
ConstTest d7 = const ConstTest('go');
print(identical(d, d7));
}




댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

플러터(flutter) 개발 참고 사이트들.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore