코딩파파로 다트 문법을 알아보자.

https://youtu.be/nRsxWt3BWzM

 

* Dart 문서

https://dart.dev/guides

 

Dart documentation

Learn to use the Dart language and libraries.

dart.dev

* Dart 웹 테스트 환경 - 예제코드 참조

https://dart.dev/#try-dart

 

Dart programming language

Dart is a client-optimized language for fast apps on any platform

dart.dev

 

* main()로 프로그램이 시작한다.

* 함수 호출구조

* 세미콜론

* 플러터를 하면서 다트문법을 자세히 참조하자.

* 에디터 문법표시

* var : 자료형 지정없이 데이터 저장
 - https://dart.dev/samples#variables

 > 스크립트 참조

 - https://dartpad.dev/?null_safety=true 

 > doumentation 영역 표시되는 환경

* 유형별 자료형

* 함수 : 함수 앞에 function 이 아니고 반환 자료형 선언

 - print 로 출력시 함수참조방법 : ${} 안에 함수호출 구문 정의

 - print 로 출력시 변수 참조방법 : $변수 정의

 - 함수형 함수정의

 - 함수를 파라미터로 정의

* 제어문 : Control flow

* String text : ['],["] 모두 문자열로 정의 가능

 - ['''] : 줄바꿈 문자열 정의 가능

 - $변수 : 문자열 안에서 변수참조 가능

 - ${계산, 함수} : 문자열 안에서 계산, 함수참조 가능

* class

 - new 생성자 생략 가능

 - 생성자(메서드)에서 파라미터 옵션속성 설정 가능, 기본값 설정 가능, 

 > Car(int sts, [String clr], [String clr2 = 'black']){}

 - named 파라미터 

 > Car(int sts, {String clr = 'black'}){}

 > Car newCar = Car(clr='red', sts:6);

 - named 파라미터는 옵션설정이 기본이고, 필수로 설정하기 위해 @설정 가능. : Flutter 기능(warring)

 > Car({int sts, @requierd String clr = 'black'}){}

 - 생성자 값 지정 간소화

 > Car({this.seat, this.color = 'black'});

 

* 예제코드 - Try Dart in your browser 

Hello World

void main() {
  print('Hello, World!');
}

Functions

// A function declaration.
int timesTwo(int x) {
  return x * 2;
}

// Arrow syntax is shorthand for `{ return expr; }`.
int timesFour(int x) => timesTwo(timesTwo(x));

// Functions are objects.
int runTwice(int x, int Function(int) f) {
  for (var i = 0; i < 2; i++) {
    x = f(x);
  }
  return x;
}

void main() {
  print('4 times two is ${timesTwo(4)}');
  print('4 times four is ${timesFour(4)}');
  print('2 x 2 x 2 is ${runTwice(2, timesTwo)}');
}

Control flow

bool isEven(int x) {
  // An if-else statement.
  if (x % 2 == 0) {
    return true;
  } else {
    return false;
  }
}

List<int> getEvenNumbers(Iterable<int> numbers) {
  var evenNumbers = <int>[];

  // A for-in loop.
  for (var i in numbers) {
    // A single line if statement.
    if (isEven(i)) {
      evenNumbers.add(i);
    }
  }

  return evenNumbers;
}

void main() {
  var numbers = List.generate(10, (i) => i);
  print(getEvenNumbers(numbers));
}

Strings

import 'dart:math' as math;

void main() {
  print('a single quoted string');
  print("a double quoted string");

  // Strings can be combined by placing them adjacent to each other.
  print('cat' 'dog');

  // Triple quotes define a multi-line string.
  print('''triple quoted strings
are for multiple lines''');

  // Dart supports string interpolation.
  final pi = math.pi;
  print('pi is $pi');
  print('tau is ${2 * pi}');
}

Collection literals

// A list literal.
const lostNumbers = [4, 8, 15, 16, 23, 42];

// A map literal.
const nobleGases = {
  'He': 'Helium',
  'Ne': 'Neon',
  'Ar': 'Argon',
};

// A set literal.
const frogs = {
  'Tree',
  'Poison dart',
  'Glass',
};

void main() {
  print(lostNumbers.last);
  print(nobleGases['Ne']);
  print(frogs.difference({'Poison dart'}));
}

Classes

// Abstract classes can't be instantiated.
abstract class Item {
  void use();
}

// Classes can implement other classes.
class Chest<T> implements Item {
  final List<T> contents;

  // Constructors can assign arguments to instance variables using `this`.
  Chest(this.contents);

  @override
  void use() => print('$this has ${contents.length} items.');
}

class Sword implements Item {
  int get damage => 5;

  @override
  void use() => print('$this dealt $damage damage.');
}

// Classes can extend other classes.
class DiamondSword extends Sword {
  @override
  final int damage = 50;
}

void main() {
  // The 'new' keyword is optional.
  var chest = Chest<Item>([
    DiamondSword(),
    Sword(),
  ]);

  chest.use();

  for (final item in chest.contents) {
    item.use();
  }
}

Compute Pi

import 'dart:math' show Random;

void main() async {
  print('Compute π using the Monte Carlo method.');
  await for (final estimate in computePi().take(100)) {
    print('π ≅ $estimate');
  }
}

/// Generates a stream of increasingly accurate estimates of π.
Stream<double> computePi({int batch = 100000}) async* {
  var total = 0; // Inferred to be of type int
  var count = 0;
  while (true) {
    final points = generateRandom().take(batch);
    final inside = points.where((p) => p.isInsideUnitCircle);

    total += batch;
    count += inside.length;
    final ratio = count / total;

    // Area of a circle is A = π⋅r², therefore π = A/r².
    // So, when given random points with x ∈ <0,1>,
    // y ∈ <0,1>, the ratio of those inside a unit circle
    // should approach π / 4. Therefore, the value of π
    // should be:
    yield ratio * 4;
  }
}

Iterable<Point> generateRandom([int? seed]) sync* {
  final random = Random(seed);
  while (true) {
    yield Point(random.nextDouble(), random.nextDouble());
  }
}

class Point {
  final double x;
  final double y;

  const Point(this.x, this.y);

  bool get isInsideUnitCircle => x * x + y * y <= 1;
}

 

+ Recent posts