본문 바로가기
프로그램 개발해서 돈벌기/flutter

4. final, const 차이점 - 완전 초보 Dart 언어 기초 문법 : flutter

by ubmuhan 2022. 12. 22.
반응형

사용 툴 - DartPad

https://dartpad.dev/

 

DartPad

 

dartpad.dev

DartPad 정보 : Based on Flutter 3.3.10 Dart SDK 2.18.6

 

final과 const는 초기 선언 시 값이 할당되면 다른 값으로 변경을 못합니다.

다른 값으로 변경을 못한다는 기능은 같지만 특성은 조금 틀립니다.

 

  • final
    run time able to add value ( new DateTime.now() O )
    앱이 실행될때 변수 선언 시 값이 할당 된다는 의미입니다.
  • const
    at build time : able to add value ( new DateTime.now() X ) : 런타임 시 값을 알수 있으므로 선언 시 에러 발생
    앱 컴파일 시 변수 선언 지점에 값이 할당 된다는 의미입니다. 그래서 DateTime.now() 함수에 쓰일 수 없습니다.

 

// 일반 변수에서 DateTime.now()
void main() {
  DateTime now = DateTime.now();
  print(now);
  
  Future.delayed(
    Duration(milliseconds: 1000), () {
      DateTime now = DateTime.now();
      print(now);
    }
  );
}
// >> 2022-12-22 15:23:33.343
// >> 2022-12-22 15:23:34.345


// final 적용
void main() {
  final DateTime now = DateTime.now();
  print(now);
  
  Future.delayed(
    Duration(milliseconds: 1000), () {
      DateTime now = DateTime.now();
      print(now);
    }
  );
}
// >> 2022-12-22 15:25:00.111
// >> 2022-12-22 15:25:01.114


// donst 적용
void main() {
  const DateTime now = DateTime.now();
  print(now);
  
  Future.delayed(
    Duration(milliseconds: 1000), () {
      DateTime now = DateTime.now();
      print(now);
    }
  );
}

// 아래와 같이 컴파일때 const를 적용한 DateTime.now()에서 에러 발생
/*
Error compiling to JavaScript:
Info: Compiling with sound null safety
lib/main.dart:2:33:
Error: Cannot invoke a non-'const' constructor where a const expression is expected.
  const DateTime now = DateTime.now();
                                ^^^
Error: Compilation failed.
*/

 

 
 
 
반응형

댓글