Flutter freezed

김민진·2021년 3월 11일
0

flutter_문법

목록 보기
2/4

flutter 에서 공개된 folio 코드를 보다가 궁금해졌다..
AppUser라는 클래스는 추상클래스이고.. _$AppUser를 상속받는다..?
kDefaultImageUrl이라는 전역 변수를 만들고...

AppUser._ 라는 것도 만들고 (사실 아직 이게 뭔지 모르겠다 싱글톤을 보면 항상 나오지만..)

factory 생성자를 만들고..(이제 이해는된다 factory한번 만들고 더이상 생성자를 만들지 않는다는 의미로 이해했다.)
@nullable이라는 어노테이션? @required라는 어노테이션..
이렇게 보다보면 내가아직 모르는게 너무나도 많다..
factory AppUser.fromJson(Map<String,dynamic> json() => _$AppUserFromJson<-- 이것도 뭔지 모르겠다..

위의 part도 사실 이해를 못하고 있고..

그래서 이게 뭔지 공부도 해보고 내가 이해하기 위해 설명도 써놓으려고 한다!

with _$AppUser는 무엇일까??

코드팩토리 강사님에게 질문해보니 코드제너레이션 이라고 하신다..
코드 제너레이션이 무엇인고 하니

미리 정의한뒤 가져다 쓴다..? 라고 나는 이해했다.

https://www.youtube.com/watch?v=pI6cXMmXBkA
해당 유튜브 영상을 보니까 확실히 어떤 방식인지는 이해가 되었다.
그치만 아직은 이걸 왜쓰는지 모르겠다 ㅜㅜ

여하튼 AppUser라는 클래스를 미리 만든뒤 해당 클래스의 내용을 가져다가 쓰는거 같다. 그러니까 상속이라는 개념으로 접근해서 사용하지..

일단 위의 기능을 테스트? 뭔지 알아보기 위해서는
freezed_annotation
build_runner
freezed 3개의 라이브러리를 넣어주어야 한다..
뭐 이런 내용은 생략하고!

유튜브 영상을 참고해서 설명하자면!

class UserWithoutGeneration {
  String name;
  int age;
  int coolness;

  UserWithoutGeneration(this.name, this.age, this.coolness);

  UserWithoutGeneration.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'],
        coolness = json['coolness'];

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
      'coolness': coolness,
    };
  }
}

이런 코드를 작성해준뒤!

import 'package:freezed_annotation/freezed_annotation.dart';

part 'user_with_generation.freezed.dart';

@freezed
abstract class UserWithGeneration with _$UserWithGeneration {
  const factory UserWithGeneration({
    String name,
    int age,
    int coolness,
  }) = _UserWithGeneration;
}

이런 코드를 또 다른 폴더에 작성해준뒤
설치했던 라이브러리를 이용해서 터미널에
flutter pub run build_runner build 커맨드를 입력해주면

part 에 넣어놨던 경로를 자동으로 만들어주며
call,copyWith,toString,비교 연산자,hashCode, 등의 코드를 자동으로 만들어 주었다... 이런걸 자동화 해주는 패키지인가??싶다

뭔가... 자동으로 다 해주니까 좋기도하고..앞으로 써먹어야 될거 같기도하고..그런 느낌??

좋긴 좋다!! 클래스 내부에 선언된 놈들이 많아지면 freezed를 쓰는게 편할거 같고 그렇지 않으면 그냥 내가 쓰는게 더 좋을거 같다..

아래의 코드를 자동으로 만들어 주었다..

혹시나 뭔지는 궁금하지만 하기는 귀찮으신분들을 위해.. 일단 작성만 ㅎㅎ;

나는 배경지식이 있으니까 내가 쓴 글이 이해가 되지만 다른 사람들도 과연 이해가 될까..싶다 어쨋든 뭐라도 작성하면 좋은거니까!

// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies

part of 'user_with_generation.dart';

// **************************************************************************
// FreezedGenerator
// **************************************************************************

T _$identity<T>(T value) => value;
UserWithGeneration _$UserWithGenerationFromJson(Map<String, dynamic> json) {
  return _UserWithGeneration.fromJson(json);
}

class _$UserWithGenerationTearOff {
  const _$UserWithGenerationTearOff();

// ignore: unused_element
  _UserWithGeneration call({String name, int age, int coolness}) {
    return _UserWithGeneration(
      name: name,
      age: age,
      coolness: coolness,
    );
  }
}

// ignore: unused_element
const $UserWithGeneration = _$UserWithGenerationTearOff();

mixin _$UserWithGeneration {
  String get name;
  int get age;
  int get coolness;

  Map<String, dynamic> toJson();
  $UserWithGenerationCopyWith<UserWithGeneration> get copyWith;
}

abstract class $UserWithGenerationCopyWith<$Res> {
  factory $UserWithGenerationCopyWith(
          UserWithGeneration value, $Res Function(UserWithGeneration) then) =
      _$UserWithGenerationCopyWithImpl<$Res>;
  $Res call({String name, int age, int coolness});
}

class _$UserWithGenerationCopyWithImpl<$Res>
    implements $UserWithGenerationCopyWith<$Res> {
  _$UserWithGenerationCopyWithImpl(this._value, this._then);

  final UserWithGeneration _value;
  // ignore: unused_field
  final $Res Function(UserWithGeneration) _then;

  @override
  $Res call({
    Object name = freezed,
    Object age = freezed,
    Object coolness = freezed,
  }) {
    return _then(_value.copyWith(
      name: name == freezed ? _value.name : name as String,
      age: age == freezed ? _value.age : age as int,
      coolness: coolness == freezed ? _value.coolness : coolness as int,
    ));
  }
}

abstract class _$UserWithGenerationCopyWith<$Res>
    implements $UserWithGenerationCopyWith<$Res> {
  factory _$UserWithGenerationCopyWith(
          _UserWithGeneration value, $Res Function(_UserWithGeneration) then) =
      __$UserWithGenerationCopyWithImpl<$Res>;
  @override
  $Res call({String name, int age, int coolness});
}

class __$UserWithGenerationCopyWithImpl<$Res>
    extends _$UserWithGenerationCopyWithImpl<$Res>
    implements _$UserWithGenerationCopyWith<$Res> {
  __$UserWithGenerationCopyWithImpl(
      _UserWithGeneration _value, $Res Function(_UserWithGeneration) _then)
      : super(_value, (v) => _then(v as _UserWithGeneration));

  @override
  _UserWithGeneration get _value => super._value as _UserWithGeneration;

  @override
  $Res call({
    Object name = freezed,
    Object age = freezed,
    Object coolness = freezed,
  }) {
    return _then(_UserWithGeneration(
      name: name == freezed ? _value.name : name as String,
      age: age == freezed ? _value.age : age as int,
      coolness: coolness == freezed ? _value.coolness : coolness as int,
    ));
  }
}

@JsonSerializable()
class _$_UserWithGeneration implements _UserWithGeneration {
  const _$_UserWithGeneration({this.name, this.age, this.coolness});

  factory _$_UserWithGeneration.fromJson(Map<String, dynamic> json) =>
      _$_$_UserWithGenerationFromJson(json);

  @override
  final String name;
  @override
  final int age;
  @override
  final int coolness;

  @override
  String toString() {
    return 'UserWithGeneration(name: $name, age: $age, coolness: $coolness)';
  }

  @override
  bool operator ==(dynamic other) {
    return identical(this, other) ||
        (other is _UserWithGeneration &&
            (identical(other.name, name) ||
                const DeepCollectionEquality().equals(other.name, name)) &&
            (identical(other.age, age) ||
                const DeepCollectionEquality().equals(other.age, age)) &&
            (identical(other.coolness, coolness) ||
                const DeepCollectionEquality()
                    .equals(other.coolness, coolness)));
  }

  @override
  int get hashCode =>
      runtimeType.hashCode ^
      const DeepCollectionEquality().hash(name) ^
      const DeepCollectionEquality().hash(age) ^
      const DeepCollectionEquality().hash(coolness);

  @override
  _$UserWithGenerationCopyWith<_UserWithGeneration> get copyWith =>
      __$UserWithGenerationCopyWithImpl<_UserWithGeneration>(this, _$identity);

  @override
  Map<String, dynamic> toJson() {
    return _$_$_UserWithGenerationToJson(this);
  }
  Map<String, dynamic> _$_$_UserWithGenerationToJson(
      _$_UserWithGeneration instance) =>
      <String, dynamic>{
        'name': instance.name,
        'age': instance.age,
        'coolenss': instance.coolness,
      };
}

abstract class _UserWithGeneration implements UserWithGeneration {
  const factory _UserWithGeneration({String name, int age, int coolness}) =
      _$_UserWithGeneration;

  factory _UserWithGeneration.fromJson(Map<String, dynamic> json) =
      _$_UserWithGeneration.fromJson;

  @override
  String get name;
  @override
  int get age;
  @override
  int get coolness;
  @override
  _$UserWithGenerationCopyWith<_UserWithGeneration> get copyWith;
}
profile
dart,c#,java 개발자! 잡다하게 해서 문제될게 없다!

0개의 댓글