Flutter

10. freezed

모리선생 2023. 4. 9. 00:46
728x90

목표

freezed 플러그인을 알아보고 bloc과 함께 사용하는 법을 연습해본다. 실사용 예제를 통해, 해당 방법을 익힌다.


*해당 내용은 본인의 개발 공부에 있어서 여러가지 참고하며 기록했던 내용을 복기하고 이해하고자 작성한 블로그 글입니다. 같이 공부를 해나가며 Flutter라는 언어에 취미를 가지신 분 들이 개념을 잡는데 도움이 되었으면 합니다. 참고한 홈페이지 등에 대해서는 각 페이지별 하단에 명시하여 두었습니다. 수정 및 문의 사항이 있으면 알려주시길 바랍니다.

 

정의

freezed (https://pub.dev/packages/freezed) 의 정의를 보면 다음과 같이 설명이 되어있다.

Dart is awesome, but defining a "model" can be tedious. We may have to:
  • define a constructor + the properties
  • override toString, operator ==, hashCode
  • implement a copyWith method to clone the object
  • handling de/serialization
On top of that, Dart is also missing features such as union types and pattern-matching.

* constructor (생성자): 클래스의 인스턴스를 생성하기 위해 사용되는 메소드로 일반적으로 클래스와 동일한 이름을 가지며, 클래스의 속성을 초기화 하는데 사용한다. 

* override: 부모 클래스에 정의된 메소드나 속성을 자식 클래스에 재정의하는 키워드. 이는 객체 지향 프로그래밍의 상속 개념을 기반으로 한다. 

* copyWith: 불변성을 유지하면서 객체를 복제하고 수정하는 메소드. Immutable 클래스에 사용.

 

즉, Freezed는 Immutable클래스를 쉽게 생성할 수 있도록 도와주면서 불변성을 유지하여야 하는 클래스를 생성하는데 필요한 많은 코드를 자동으로 생성할 수 있습니다. Freezed는 JSON 직렬화와 같은 작업 수행해도 도움을 줄 수 있습니다. 또한 중요한 점이라고 한다면 불변의 클래스를 다루기 때문에 생성자와 함께 선언된 필드를 변경하는 것을 허용하지 않습니다. 다만 새로운 객체를 만들어서 필드를 수정해야 합니다. 이를 위해 freezed는 Data classes를 사용합니다.

 

freezed 사용하기

1. 설치 (디펜던시 추가)

dependencies:
  freezed_annotation:

dev_dependencies:
  build_runner:
  freezed:
  /// Option (만약, toJson 및 fromJson 기능 사용을 원할 시 추가)
  json_serializable:

2. 기본 문법

Flutter 공식 홈페이지에 있는 구문을 직접 가져와서 분석하면서 확인해봅시다. 이 코드에서는 Person 클래스에 firstName, lastName, age 값들을 저장하고 Person factory constructor에 정의를 하였습니다. main.freezed.dart 및 다른 부분에서 오류 표시가 날 텐데 아직, 파일이 존재하지 않아 그런것이니 그냥 넘어가시면 됩니다. 

// This file is "main.dart"
import 'package:freezed_annotation/freezed_annotation.dart';

// required: associates our `main.dart` with the code generated by Freezed
part 'main.freezed.dart';
// optional: Since our Person class is serializable, we must add this line.
// But if Person was not serializable, we could skip it.
part 'main.g.dart';

@freezed
class Person with _$Person {
  const factory Person({
    required String id,
    required String Name,
    required int age,
  }) = _Person;

  factory Person.fromJson(Map<String, Object?> json) => _$PersonFromJson(json);
}

코드를 작성하고 난 뒤에 터미널에서 다음의 code generation을 실행합니다.

flutter pub run build_runner build

끝입니다. 다양한 글들이 터미널에 적히기 시작하면서 'main.freezed.dart'와 'main.g.dart'라는 파일이 새롭게 생성되어 있을 것입니다. freezed의 설명에 따르면 다음의 3가지가 만들어졌을 것입니다.

  • copyWith : for cloning the object with different properties
  • toString: override listing all the properties of the object
  • operator == & hashcode

이제 이 파일들에 자동으로 생성된 것들이 무엇인지 확인해봅시다.

 

3. constructor와 property를 자동생성

일단은 간단하게 앱을 만들어봅니다.

import 'package:flutter/material.dart';
import 'package:freezed_practice_1/person.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'freezed',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('freezed')),
      body: Column(
        children: [
          
        ],
      ),
    );
  }
}

그다음, 내가 입력하려고 하는 Person의 정보를 입력해줍니다.

(...)

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('freezed')),
      body: Column(
        children: [
          Text(person1.id),
          Text(person1.name),
          Text(person1.age.toString()),
          Text(person1.toString()),
        ],
      ),
    );
  }
  
(...)

3-1. toString override, Json method

여기서 보면 toString()함수를 override를 하였습니다. int를 그냥 person1.age로 부르려고 했다면 분명 에러가 발생을 했을꺼에요. 아마 type이 다르다는 메시지가 출력이 될겁니다. 이때에는 toString()을 붙임으로써 정보 제공을 위한 형태로 출력을 하면됩니다.

 

그럼 Json은? 동일합니다. fromJson() 혹은 toJson()를 적어 자동으로 작성해주도록 하는 것이죠.

 

그럼 이렇게 나타나게 되죠.

이외에도 

  • == & hasCode override
  • Assert
  • method & getter
  • Copy

등 부분이 있으나, 다음 장에 알아보도록 하겠습니다.

 

참고

(1) Dart 공식 홈페이지 https://pub.dev/packages/freezed

(2) Codefactory 블로그 https://blog.codefactory.ai/flutter/freezed/

(3) Codefactory 유튜브 https://www.youtube.com/watch?v=i5p6wXLAX7I&t=440s 

 

728x90

'Flutter' 카테고리의 다른 글

11. BLoC  (0) 2023.04.09
10-1. freezed의 다른 기능들  (0) 2023.04.09
7-2. Throttle 실습  (0) 2023.04.03
7-1. Debounce 실습  (0) 2023.04.03
[Practice] shared preference  (0) 2023.04.02