ABOUT ME

Today
Yesterday
Total
  • Flutter 기본1(변수,상수,연산자)
    Flutter 2022. 1. 27. 11:27

    Flutter은 Dart 언어를 사용하는데 기본적으로 다른 언어(java)랑 비슷?하다. 내가 봣을때 다른것들을 정리하려한다.

    코드는 아래 dartpad를 통해 돌려보면서 확인

    https://dartpad.dev/ 

    Dart 변수

    var

    var를 선언과 동시에 할당하면 type이 할당된 type으로 고정이되고

    var를 선언과 동시에 할당하지 않으면 Dynamic type이 된다.

    void main() {
      var value1 = 'test'; // value1은 String type이됨 
      value1 = 1; // compile error, String에 int type를 넣으려고 하니 error
      
      var value2;
      value2 = 'test'; // 선언후 할당 했기에 Dynamic type 
      print(value2); // test, value2 is String
      value2 = 1; // error가 발생 하지 않음
      print(value2); // 1, value2 is int
    }

    List

    forEach, in

    둘다 사용 할수 있는데 Dart 코드스타일에서는 in을 권장 하고 있다.
    다만 객체 안에 정의되어 있는 함수를 반복 사용하려면 forEach를 사용하라고 하고 있음

    Note that this guideline specifically says “function literal”. If you want to invoke some already existing function on each element, forEach() is fine.
    void main() {
      List<String> fruits = ['Apple', 'Banana', 'Kiwi'];
    
      fruits.forEach((fruit) {
        print('${fruit}!');
      }); // bad
    
      for (String fruit in fruits) {
        print('${fruit}!!');
      } // good
      
      //people.forEach(print); good
    }

    map

    새로운 리스트를 만들때 사용

    void main() {
      List<String> fruits = ['Apple', 'Banana', 'Kiwi'];
      List<String> newFruits = fruits.map((e) {
        return 'My name is ${e}';
      });
      print(newFruits);
      print(newFruits.toList()); // 새로운 리스트
    }

    asMap

    list타입을 Map으로 변경, 변경된 Map의 key가 index가 됨, index 값이 필요 할때 사용

    void main() {
      List<int> numbers = [10, 20, 30, 40, 50];
      Map newNumbers = numbers.asMap();
      print(numbers); //[10, 20, 30, 40, 50]
      print(newNumbers); //{0: 10, 1: 20, 2: 30, 3: 40, 4: 50}
    }

    Map

    entries

    루푸를 돌수 있으며 결과값으로 list를 생성 할 수 있음

    void main() {
      Map<String, int> fruitCount = {
        'Apple': 3,
        'Banana': 4,
        'Kiwi': 10,
      };
    
      Iterable newFruitCount =
          fruitCount.entries.map((e) => '${e.key} / ${e.value}');
      print(newFruitCount.toList());//[Apple / 3, Banana / 4, Kiwi / 10]
    }

    상수

    한번 값을 할당하고 변경 할 수 없는 것을 상수라 한다. 

    void main() {
      final String firstName = 'Yakuza';
      const String lastName = 'Dev';
      firstName = 'Dev'; // err
      lastName = 'Dev'; // err
    }

    final과 const 차이

    void main() {
      final DateTime now = DateTime.now(); // 가능
      const DateTime now = DateTime.now(); // err, 불가 
      print(now);
    }

    연산자

    ??= (Null-aware operator)

    변수의 값이 null인 경우 값을 할당. ??이게 변수가 null인지 확인

    void main() {
      var name = null;
      name ??= 'na';
      print(name); //  na
    
      name ??= 'Dev';
      print(name); // na
    }

    ?? // 이거 먼지 모르겠음

    void main() {
      var name = null;
      if(name??false){
        print(false);
      }
      if(name??true){
        print(true);
      }
    }
    // true 출력.

    함수

    Optional 파라메터

    []를 사용하면 optional하게 사용 가능, [ ] 안에 들어오는 파라메터는 없을수도 있으니깐 기본값을 설정해주어야 함.

    String add(int a, int b, [int c = 0]) {
      int sum = a + b + c;
      return 'Sum: $sum';
    }
    
    void main() {
      print(add(1, 1));
      print(add(1, 1, 1));
    }

    Named 파라메터

    { } 이걸 사용하면 호출시 파라메터 명을 직접적으로 호출해 명확하게 호출 가능

    (아마 이기능 사라질꺼 같음...)

    String add(int a, int b, {int c = 0, int d = 0}) {
      int sum = a + b + c + d;
      return 'Sum: $sum';
    }
    
    void main() {
      print(add(1, 1));
      print(add(1, 1, c: 1));
      print(add(1, 1, d: 1));
      print(add(1, 1, c: 1, d: 1));
    }

    typedef

    함수를 파라메터로 전달 할 수 있음. 파라메터로 전달 받을 함수의 타입을 선언하고 지정 할 수 있음
    (이것도 다른 언어에서는 좀더 쉽게 제공 해주는데..)

    typedef Operator(int n, int m);
    
    String add(int a, int b) {
      int sum = a + b;
      return 'Sum: $sum';
    }
    
    String calculate(int x, int y, Operator op) {
      return op(x, y);
    }
    
    void main() {
      print(add(2, 1));
    
      Operator op = add;
      print(op(2, 1));
    
      print(calculate(2, 1, add));
    }

     

     

    참조: https://dev-yakuza.posstree.com/ko/flutter/dart/variable/

Designed by Tistory.