Dart 기초

설아아빠·2022년 1월 3일
0
post-thumbnail

Dart 기초

  • 내가 보려고 작성
  • 원본링크 dart.dev

잘 이해가 안되는것

Variables

변수 선언

  • var 로 선언하는 경우 String으로 초기화 했으면 다른 타입 할당 불가
  • Object로 선언하였으면 다른 타입 할당 가능
main() {
  var name = 'test';
  Object name1 = 'bob';
  String name2 = '';
}

NullAble

  • 전역변수는 선언시 초기화 되어야함 선언시 초기화하지 않을경우 ?로 nullable을 명시
  • 함수 안에서는 초기화 하지 않고 선언 가능
int no; //error (함수 안에서는 가능 단 사용하기 전에 초기화 해야함)
int no = 1; //no error
int? lineCount; //nullable

Late

  • 선언 후에 초기화되는 nullable이 아닌 변수
late String name3;

final and const

  • 변경할수 없는 오브젝트
main() {
  const name = 'test';
  final name = 'test';

  var name = const[]; //unmodifiable list
  const name = []; //이것도 위에랑 동일함  
}

Built-in Types

타입목록

  • Numbers (int, double)
  • Strings (String)
  • Booleans (bool)
  • Lists (List, also known as arrays)
  • Sets (Set)
  • Maps (Map)
  • Runes (Runes; often replaced by the characters API)
  • Symbols (Symbol)
  • The value null (Null)

일부 다른 유형

  • Object: 를 제외한 모든 Dart 클래스의 수퍼클래스입니다 Null.
  • Future및 Stream: 비동기 지원에 사용됩니다 .
  • Iterable: for-in 루프 및 동기 생성기 함수에서 사용 됩니다.
  • Never: 표현식이 평가를 성공적으로 완료할 수 없음을 나타냅니다. 항상 예외를 throw하는 함수에 가장 자주 사용됩니다.
  • dynamic: 정적 검사를 비활성화할 것임을 나타냅니다. 일반적으로 Object또는 Object?대신 사용해야 합니다.
  • void: 값이 사용되지 않음을 나타냅니다. 종종 반환 유형으로 사용됩니다.

Numbers

  • num으로 선언하여 int와 double 두가지로 왔다갔다 사용이 가능
main() {
  var x = 1;
  var hex = 0xDEADBEEF;
  var exponent = 8e5;

  num x = 1; // x can have both int and double values
  x += 2.5;

  double z = 1; // Equivalent to double z = 1.0.
}
  • 형변환
// String -> int
var one = int.parse('1');

// String -> double
var onePointOne = double.parse('1.1');

// int -> String
String oneAsString = 1.toString();

// double -> String
String piAsString = 3.14159.toStringAsFixed(2);

Strings

  • 선언
main() {
  var s1 = 'Single quotes work well for string literals.';
  var s2 = "Double quotes work just as well.";
  var s3 = 'It\'s easy to escape the string delimiter.';
  var s4 = "It's even easier to use the other delimiter.";
}
  • 줄바꿈 (+ 로도 가능하지만 그냥 줄 바꾸기만해도 결과 같음)
main() {
  var s1 = 'String '
      'concatenation'
      " works even over line breaks.";
  var s2 = 'The + operator ' + 'works, as well.';
}
  • ``` 으로 바로 그대로 여러 라인 출력이 가능함
main() {
  var s1 = '''
You can create
multi-line strings like this one.
''';

  var s2 = """This is also a
multi-line string.""";
}

List

  • 선언
main() {
  var list = [
    'Car',
    'Boat',
    'Plane',
  ];
}
  • 펼치기
main() {
  var list = [1, 2, 3];
  var list2 = [...list, 4];
}
  • 선언과 동시에 if,for 사용이 가능함
main() {
  bool promoActive = true;
  var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];

  var listOfInts = [1, 2, 3];
  var listOfStrings = [
    '#0',
    for (var i in listOfInts) '#$i'
  ];
}

Sets

  • 선언
main() {
  var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
}
  • 빈 Sets 선언하면서 타입 설정이 가능함
main() {
  var names = <String>{};
  Set<String> names = {};
}

Maps

  • 선언
main() {
  var gifts = {
    // Key:    Value
    'first': 'partridge',
    'second': 'turtledoves',
    'fifth': 'golden rings'
  };
}

Runes and grapheme clusters

  • 유니코드 문자를 다룰때 사용한다
import 'package:characters/characters.dart';

void main() {
  var hi = 'Hi 🇩🇰';
  print(hi);
  print('The end of the string: ${hi.substring(hi.length - 1)}');
  print('The last character: ${hi.characters.last}\n');
}

Functions

선언

bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

//스크립트 언어처럼 선언가능
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

Parameters

  • 선언시 nullable로 설정 가능
void enableFlags({bool? bold, bool? hidden}) {
}
  • Optional 파라미터 선언
    • []로 파라미터를 선언함
main(List<String> arguments) {
  String say(String from, String msg, [String? device]) {
    var result = '$from says $msg';
    if (device != null) {
      result = '$result with a $device';
    }
    return result;
  }

  //위 함수는 아래처럼 초기화 시키면서 넘길수도 있음
  String say1(String from, String msg, [String device = 'carrier pigeon']) {
    var result = '$from says $msg with a $device';
    return result;
  }

  print(say('test', 'zxcv')); //이렇게 가능하고
  print(say('test', 'zxcv', 'iphone')); //이렇게도 가능함
}

Functions as first-class objects

  • 함수를 다른 함수에 매개변수로 전달
main() {
  void printElement(int element) {
    print(element);
  }

  var list = [1, 2, 3];

// Pass printElement as a parameter.
  list.forEach(printElement);
}

Anonymous functions

  • 익명함수
main() {
  const list = ['apples', 'bananas', 'oranges'];
  list.forEach((item) {
    print('${list.indexOf(item)}: $item');
  });
}

Lexical scope

  • 다트는 스코프 언어다
main() {
  bool topLevel = true;

  void main() {
    var insideMain = true;

    void myFunction() {
      var insideFunction = true;

      void nestedFunction() {
        var insideNestedFunction = true;

        assert(topLevel);
        assert(insideMain);
        assert(insideFunction);
        assert(insideNestedFunction);
      }
    }
  }
}

Lexical closures

Function makeAdder(int addBy) {
  return (int i) => addBy + i;
}

void main(List<String> arguments) {
  var add2 = makeAdder(2);
  print(add2);
  print(add2(1));

  var add4 = makeAdder(4);
  print(add4);
  print(add4(3));
}
Result

Closure: (int) => int
3
Closure: (int) => int
7

Conditional expressions

  • 두가지 방식을 지원
//일반적인 방식
var visibility = isPublic ? 'public' : 'private';
//??로 표현한 방법
String playerName(String? name) => name ?? 'Guest';

void main(List<String> arguments) {
  String playerName(String? name) => name ?? 'Guest';

  print('null : ${playerName(null)}');
  print('value : ${playerName('test')}');
}

Cascade notation

  • ..체이닝을 이용해서 동일한 개체에 대해 일련의 작업을 연속해수 수행이 가능함
class Man {
  late String name;
  late int age;

  printMan() {
    print("man : $name $age");
  }
}

void main() {
  var man = Man()
    ..name = 'test'
    ..age = 16
    ..printMan();
}
Result

man : test 16

If and else

  • 일반적인 프로그래밍 언어와 같음
main() {
  if (isRaining()) {
    you.bringRainCoat();
  } else if (isSnowing()) {
    you.wearJacket();
  } else {
    car.putTopDown();
  }
}

For loops

  • 클로저(함수를 만드는 함수) 전달 가능
void main() {
  var callbacks = [];

  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print(i));
  }

  for (var callback in callbacks) {
    callback();
  }
}

Exceptions

main() {
  try {
    breedMoreLlamas();
  } on OutOfLlamasException {
    // A specific exception
    buyMoreLlamas();
  } on Exception catch (e) {
    // Anything else that is an exception
    print('Unknown exception: $e');
  } catch (e) {
    // No specified type, handles all
    print('Something really unknown: $e');
  }
}

Class

Instance variables

class Point {
  double? x; // Declare instance variable x, initially null.
  double? y; // Declare y, initially null.
  double z = 0; // Declare z, initially 0.
  late double x1;
}

Methods

  • Operator를 이용해 연산자와 메소드를 함께 쓸수 있음?
    • Operators
<	+	|	>>>
>	/	^	[]
<=	~/	&	[]=
>=	*	<<	~
–	%	>>	==
class Vector {
  final num x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);

  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  Vector operator /(Vector v) => Vector(x / v.x, x / v.y);
}

void main() {
  final v = Vector(2, 2);
  final w = Vector(4, 10);

  final t = v + w;
  final n = v / w;

  print('${t.x},${t.y}');
  print('${n.x},${n.y}');
}
Result
6,12
0.5,0.2

Adding features to a class: mixins

  • with를 이용한 다중 상속
  • Override되는 메소드는 가장 마지막에 with한 클래스의 메소드를 사용함
class A {}

class B {}

class D {}

class E {
  print1() {
    print('e print');
  }
}

mixin F {
  print1() {
    print('f print');
  }
}

class C extends A with B, E, D, F {}
//class C extends A with B, D, F, E {}

void main() {
  var c = C();
  c.print1();
}
  • on을 이용해서 재사용 할수있는 오브젝트를 명시 가능
class Man {}

mixin Man1 on Man {}

class C with Man1 {} //사용불가

class Man2 extends Man with Man1 {} //사용 가능
profile
back-end(java), front-end (조금)

0개의 댓글