Flutter

[Flutter] VS Code Dart Data Class Generator Extention 사용법

izongg 2024. 8. 26. 13:00
반응형

요즘 flutter에서 모델을 선언할 때  json_serializable나 freeze를 통해 code generator로 구현하는 경우가 많다.

하지만 code generator에 의존하는 것은 좋다고만 할 수 없다.

 

왜냐하면 패키지에 의존하는 것이기 때문에, 패키지 지원이 중단될 경우 엄청난 유지보수가 필요할수가 있다. 또한 generate 된 코드 파일은 git에 올라가지 않도록 하는 경우가 대부분이다. 따라서 프로젝트를 가져와서 build runner를 실행하기 전까지는 숨겨진 코드이기 때문에 문제가 발생할 수 있다. 

 

따라서 VS Code에서 지원하는 Dart Data Class Generator를 사용해보았다.

 

https://marketplace.visualstudio.com/items?itemName=dotup.dart-data-class-generator

 

Dart Data Class Generator - Visual Studio Marketplace

Extension for Visual Studio Code - Create dart data classes easily, fast and without writing boilerplate or running code generation.

marketplace.visualstudio.com

 

 

 

설치 후 모델을 작성해보았다.

 

모델 형식만 정하고 난 후, ( cmd + . ) 을 누르면 이렇게 코드를 만들어주는 기능이 있다.

필요한 기능만 사용해도되고, Generate data class 를 눌러서 모든 기능을 작성해도 된다.

 

다음은 모든 기능을 추가한 코드이다.

 

import 'dart:convert';

class CountModel {
  int count;
  String name;
  CountModel({
    required this.count,
    required this.name,
  });
  
  CountModel copyWith({
    int? count,
    String? name,
  }) {
    return CountModel(
      count: count ?? this.count,
      name: name ?? this.name,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'count': count,
      'name': name,
    };
  }

  factory CountModel.fromMap(Map<String, dynamic> map) {
    return CountModel(
      count: map['count'] as int,
      name: map['name'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory CountModel.fromJson(String source) => CountModel.fromMap(json.decode(source) as Map<String, dynamic>);

  @override
  String toString() => 'CountModel(count: $count, name: $name)';

  @override
  bool operator ==(covariant CountModel other) {
    if (identical(this, other)) return true;
  
    return 
      other.count == count &&
      other.name == name;
  }

  @override
  int get hashCode => count.hashCode ^ name.hashCode;
}

 

반응형