다른 언어와 플러터를 함께 하시는 분들은 항상 말씀하시더라구여.. 플러터, 다트 공식문서는 최고라고..
아직도 와닿지 않지만 대부분 저보다 먼저 이 길을 걸어가신 분들의 이야기는 맞더라구여 그러니까 제가 하고 싶은 말은 저 또 기초로 돌아왔습니다. 껄껄 이번에는 공식문서를 따라 잘 정리하면서 공부해보려고 합니다.🥲
Language Tour로 진입하기 전 간단한 설명을 보며 워밍업을 해봅시다.
Hello world
모든 앱에는 main() 함수가 있습니다. console에 텍스트를 표시하기 위해 print() 함수를 사용합니다.
void main() {
print('Hello, World!');
}
변수
다트는 type safe언어로 대부분의 변수는 타입 추론이 가능하기 때문에 명시적인 타입을 필요로 하지 않습니다.
* type safe: 타입에 안정적인 것을 의미하며 연산이나 조작에 있어서 논리적이지 않은 것에 엄격히 체크를 하여 runtime시에 이로 인한 오류가 발생하지 않도록 합니다.
void main() {
var name = 'Dog';
var year = 2022;
var dog = ['Golden Retriever', 'Poodle', 'Old English Sheepdog', 'Dachshund'];
var description = {
'tags': ['poodle'],
'comment': ['briliant', 'cute']
};
print(name);
print(year);
print(dog);
print(description);
}
//출력
Dog
2022
[Golden Retriever, Poodle, Old English Sheepdog, Dachshund]
{tags: [poodle], comment: [briliant, cute]}
제어문
다트는 일반적인 제어문을 지원합니다.
void main() {
//if문
if (samsung >= 90000) {
print('Bitten');
} else if (year >= 70000) {
print('Safe');
}
//for문
for (final dog in dogs) {
print(dog);
}
//for문
for (int month = 1; month <= 12; month++) {
print(month);
}
//while문
while (year < 2022) {
year += 1;
}
}
함수
각 함수의 인수 및 반환 값의 유형을 지정하는 것이 좋습니다.
void main() {
int makeOrder(int count, int price) {
return count * price;
}
int newOrder = makeOrder(3, 2000);
print(newOrder);
}
함수가 단일문일 때는 arrow함수를 사용해서 표현할 수 있습니다.
클래스
class Idol{
String name;
DateTime? debutday;
// Read-only non-final property
int? get debutYear => debutday!.year;
// Constructor, with syntactic sugar for assignment to members.
Idol(this.name, this.debutday) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Idol.unlaunched(String name) : this(name, null);
// Method.
void describe() {
print('$name가 데뷔한 연도는 $debutday입니다.');
}
}
위에서 정의한 Idol 클래스를 사용합니다.
void main() {
Idol blackpink = Idol('BlackPink', DateTime(2016, 8));
blackpink.describe();
}
//출력
BlackPink가 데뷔한 연도는 2016-08-01 00:00:00.000입니다.
class BoyIdol extends Idol{
int membersCount;
BoyIdol(String name, DateTime debutday, this.membersCount)
: super(name, debutday);
}
Idol 클래스를 상속받는 BoyIdol 클래스를 만들어봤습니다.
Mixins
Mixin은 여러 클래스 계층에서 코드를 재사용하는 방법입니다.
mixin Introduce{
void introduceMember(){
print('안녕하세요 좋은 아침입니다.');
}
}
클래스에 mixin의 기능을 추가하려면 mixin을 사용하여 클래스를 extends하면 됩니다.
class BoyIdol extends Idol with Introduce{
// ...
}
인터페이스와 추상 클래스
먼저 다트에는 인터페이스 키워드가 없습니다. 대신 모든 클래스는 암시적으로 인터페이스를 정의합니다. 따라서 모든 클래스를 구현할 수 있습니다.
class GirlIdol implements Idol{
// ...
}
추상 클래스를 만들어 특정 클래스로 확장하거나 구현할 수 있습니다. 추상 클래스는 (빈 본문이 있는) 추상 메서드를 포함할 수 있습니다.
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
Async
콜백 지옥을 피하고 async와 await을 이용하여 코드를 더욱 읽기 쉽게 만들 수 있습니다.
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
그리고 async*를 사용하면 stream으로 만들 수 있습니다.
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (final object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
예외처리
if (count == 0) {
throw StateError('There's Nothing');
}
예외를 잡기위해 try ~ catch 구문을 사용합니다.
try {
for (final object in flybyObjects) {
var description = await File('$object.txt').readAsString();
print(description);
}
} on IOException catch (e) {
print('Could not describe object: $e');
} finally {
flybyObjects.clear();
}
참고자료
'Dart' 카테고리의 다른 글
A tour of the Dart language 4탄 [Spread Operator ... ] (0) | 2022.01.06 |
---|---|
A tour of the Dart language 3탄 [Variables] (0) | 2021.12.30 |
A tour of the Dart language 2탄 [keyword] (0) | 2021.12.27 |
[Dart] final과 const의 차이점&정의를 알아봅니다. (0) | 2021.12.08 |
Dart 문법에 대한 간단한 정리 (0) | 2021.07.16 |