0. 들어가기 앞서
- flutter 하는데 dart를 1도 모르니 이해가 안되는 부분이 많아서 dart를 속성으로 대충 해보기로 했네요 :)
1. hello world
void main() {
print('Hello, World!');
}
- 모든 app은 main() 함수를 가지고 있습니다. (진입점)
- console 화면에 보여주기 위해서는 top-level 함수인 print를 사용하면 됨
2. variables (변수)
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
'tags': ['saturn'],
'url': '//path/to/saturn.jpg'
};
일반적으로 타입에 안전합니다. (var 라고 명기하면 내부적으로 알아서 인식됨 ) , type inference ( 타입 추론이 내장됨 )
variables 더 읽어보기 - 다음시간 정도에 다시 정독해서 글을 올려 보겠습니다.
3. control flow statements (흐름 제어 구문)
if (year >= 2001) {
print('21st century');
} else if (year >= 1901) {
print('20th century');
}
for (var object in flybyObjects) {
print(object);
}
for (int month = 1; month <= 12; month++) {
print(month);
}
while (year < 2016) {
year += 1;
}
- if, else if
- for, for in
- while
- 자세히 읽어보기 break, continue, switch, case, assert
4. functions (함수)
int fibonacci(int n) {
if (n == 0 || n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
var result = fibonacci(20);
- 각각의 함수는 변수와 리턴해 줄 값을 넣어 주도록 합니다.
flybyObjects.where((name) => name.contains('turn')).forEach(print);
- arrow funtion (화살표 함수) 또한 지원합니다.
- 무기명 함수(anonymous function)에서 인자값을 패스할때 유용합니다.
- functions 더 읽어보기
5. comments (주석)
// This is a normal, one-line comment.
/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.
/* Comments like these are also supported. */
- 일반적으로
//
을 사용 - 물론
/* */
또한 사용 가능 합니다.
6. import (불러들이기)
// Importing core libraries
import 'dart:math';
// Importing libraries from external packages
import 'package:test/test.dart';
// Importing files
import 'path/to/my_other_file.dart';
- 다른 라이브러리에 정의된 API를 호출하여 사용할 때 이용됩니다.
- import 더 읽어보기 show, hide, deferred 등
6. Classes (클래스)
class Spacecraft {
String name;
DateTime launchDate;
// Constructor, with syntactic sugar for assignment to members.
// 생성자 맴버변수의 값 할당이 이뤄짐
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
// 초기화 코드가 들어가는 구간
}
// Named constructor that forwards to the default one.
// 기본 생성자로 전달되는 명명 된 생성자
Spacecraft.unlaunched(String name) : this(name, null);
int get launchYear =>
launchDate?.year; // read-only non-final property
// Method.
// 메소드
void describe() {
print('Spacecraft: $name');
if (launchDate != null) {
int years =
DateTime.now().difference(launchDate).inDays ~/
365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
위 예제는 아래와 같이 구성되어 있습니다.
- 3개의 속성(properties)
- 2개의 생성자(constructors)
- 1개의 메소드(method)
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();
var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();
사용 예시
7. inheritance (상속)
class Orbiter extends Spacecraft {
num altitude;
Orbiter(String name, DateTime launchDate, this.altitude)
: super(name, launchDate);
}
dart는 단일상속(single inheritance)을 지원합니다. (자바 같네요 흠..)
8. mixins (확장)
Mixins은 여러 클래스 계층 구조에서 코드를 재사용하는 방법입니다. 다음 클래스는 믹스 인으로 작동 할 수 있습니다.
class Piloted {
int astronauts = 1;
void describeCrew() {
print('Number of astronauts: $astronauts');
}
}
mixin의 기능을 클래스에 추가하려면 mixin을 사용하여 클래스를 확장하면됩니다.
class PilotedCraft extends Spacecraft with Piloted {
// ···
}
PilotedCraft 클래스는 이제 astronauts 필드와 describeCrew() 메소드를 가지게 되었습니다.
9. interfaces and abstract classes (인터페이스와 추상 클래스)
class MockSpaceship implements Spacecraft {
// ···
}
dart에서는 interface 키워드가 없습니다. 대신 강제적으로 모든 클래스에서 구현을 해야 됩니다.
위 같은 경우 Spacecrft의 메소드를 MockSpaceship에서 구현 해야 됨
abstract class Describable {
void describe();
void describeWithEmphasis() {
print('=========');
describe();
print('=========');
}
}
클래스에 의해 확장 (또는 구현) 될 추상 클래스를 생성 할 수 있습니다. 추상 클래스는 빈 몸체를 가진 추상 메소드를 포함 할 수 있습니다.
10. async (비동기)
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
await Future.delayed(oneSecond);
print(message);
}
콜백 지옥에서 탈출하기 위해 async와 await을 사용합니다.
위 내용은 아래와 동일 합니다.
Future<void> printWithDelay(String message) {
return Future.delayed(oneSecond).then((_) {
print(message);
});
}
- 아래 예제는 async와 await를 보여주는 간단한 예시 입니다.
Future<void> createDescriptions(Iterable<String> objects) async {
for (var object in objects) {
try {
var file = File('$object.txt');
if (await file.exists()) {
var modified = await file.lastModified();
print(
'File for $object already exists. It was modified on $modified.');
continue;
}
await file.create();
await file.writeAsString('Start describing $object in this file.');
} on IOException catch (e) {
print('Cannot create description for $object: $e');
}
}
}
- async* 를 활용하여 스트림 생성을 가독성 좋게 해줍니다.
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
for (var object in objects) {
await Future.delayed(oneSecond);
yield '${craft.name} flies by $object';
}
}
11. exceptions (예외처리)
- 애러 발생 시키기
if (astronauts == 0) {
throw StateError('No astronauts.');
}
- try 구문과 on catch를 사용한 예외 처리 방식
try {
for (var 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();
}