[dartlang] 다트 기초 과정

in #dart5 years ago (edited)

0. 들어가기 앞서

출처 : https://www.dartlang.org/samples

  • 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;
}

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';

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();
}

Sponsored ( Powered by dclick )

dclick-imagead

Sort:  

오옹~ 그러고 보니 flutter 공부시작했다가 node.js 한다고... flutter 까먹고 있었네요.

전 아직도 node가 좋긴 하네요 ㅜㅜ 그래도 폰개발도 해야되니 ㅋㅋ

진짜 짱나는건 json임 class를 일일이 만등어야 되서요 ㅜㅜ node나 python은 그냥 씀되는데 흑흑

Posted using Partiko Android

다트 때문에 저는 모바일앱을 리액트 네이티브로 개발하려구요. 플러터가 더좋은데 공부하는데 시간이 부족합니다.

결국 플러터 덕분에 다트 공부를 시작하셨군요. ㅎㅎㅎ
덕분에 배우고 갑니다.

기본을 뛰어넘고는 역시 벽에 부딛쳐서요 :)

열공 해봐야죠 ㅋ

Posted using Partiko Android

저도 다트라는 벽에 부딪쳐서 그만 플러터를 손에서 놓고 말았어요 ㅠ
원사마님이 포스팅 하시면 그거 보고 다시 공부할려고요.
감사합니다.

Hi @wonsama!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 3.735 which ranks you at #4949 across all Steem accounts.
Your rank has improved 34 places in the last three days (old rank 4983).

In our last Algorithmic Curation Round, consisting of 234 contributions, your post is ranked at #193.

Evaluation of your UA score:
  • You're on the right track, try to gather more followers.
  • You have already convinced some users to vote for your post, keep trying!
  • Try to improve on your user engagement! The more interesting interaction in the comments of your post, the better!

Feel free to join our @steem-ua Discord server

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 69626.36
ETH 3667.86
USDT 1.00
SBD 3.82