[Flutter] 스나이퍼팩토리 Flutter 중급과정 (3)

GONG·2023년 4월 25일
0

24일차 과제 링크 👉 24일차 과제

factory 생성자

  • 객체를 직접 생성하지 않고, 객체를 생성하는 다른 방법을 제공함
  • 일반적으로 객체를 생성하고 반환하기 전에 추가적인 로직을 수행하려는 경우에 사용됨
    class MyClass {
      final int value;
    
    	// 기본 생성자
      MyClass(this.value);
    	
    	// factory 생성자
    	// 문자열을 받고 그 문자열으로 객체를 생성하여 반환
      factory MyClass.fromString(String str) {
        final parts = str.split('-');
        final value = int.parse(parts.last);
    		// 객체를 직접 생성하지 않고 이미 생성된 객체를 반환하는 방식으로 동작함
        return MyClass(value);
      }
    }

Json Serialization

  • json 직렬화
  • 객체를 json 문자열로 변환하거나, 반대로 json 문자열을 객체로 변환하는 과정 → json 데이터를 class에 맞게 세팅해주는 것

Person 클래스

class Person {
  String name;
  int age;
  
  Person(this.name, this.age);
}

직렬화

  • Person 객체를 json 문자열로 직렬화
    import 'dart:convert';
    
    Person person = Person('John', 30);
    String jsonStr = jsonEncode(person);
    print(jsonStr); // {"name":"John","age":30}

역직렬화

  • json 문자열을 Person 객체로 역직렬화
    import 'dart:convert';
    
    String jsonStr = '{"name":"John","age":30}';
    Person person = Person.fromJson(jsonDecode(jsonStr));
    print(person.name); // John
    print(person.age); // 30

fromJson()

  • Person 클래스에 fromJson() 메서드 만들어서 json 객체 만들어내기
  • json.Decode() 함수로 파싱된 Map 객체를 fromJson() 메서드에 전달해서 json 문자열을 Person 객체로 역직렬화
    class Person {
      String name;
      int age;
      
      Person(this.name, this.age);
      
      factory Person.fromJson(Map<String, dynamic> json) {
        return Person(json['name'], json['age']);
      }
    }

연습

Meowfacts

  • https://meowfacts.herokuapp.com/
  • 고양이에 대한 사실을 랜덤으로 전달해주는 오픈 API
    {
    	"data": [
    		"Julius Ceasar, Henri II, Charles XI, and Napoleon were all afraid of cats."
    	]
    }
  • json 데이터 받아와서 MeowFact 인스턴스 만들어보기
    import 'package:dio/dio.dart';
    
    class MeowFact {
      List<String> data;
    
      MeowFact({required this.data});
    
      factory MeowFact.fromMap(Map<String, dynamic> map) {
        var data = List<String>.from(map['data']);
        return MeowFact(data: data);
      }
    
      
      String toString() => 'MeowFact($data)';
    }
    
    void main() async {
      Dio dio = Dio();
      var url = 'https://meowfacts.herokuapp.com/';
      for (int i=0; i<10; i++) {
        var res = await dio.get(url);
        if (res.statusCode == 200) {
          var fact1 = MeowFact.fromMap(res.data);
          print(fact1);
        }
      }
    }

CatFact

  • https://catfact.ninja/fact
  • 고양이에 대한 사실을 랜덤으로 전달해주는 오픈 API
    {
    	"fact": "Cats are extremely sensitive to vibrations. Cats are said to detect earthquake tremors 10 or 15 minutes before humans can.",
    	"length": 122
    }
  • json 데이터 받아와서 CatFact 인스턴스 만들어보기
    import 'package:dio/dio.dart';
    
    class CatFact {
      String fact;
      int length;
    
      CatFact({required this.fact, required this.length});
    
      factory CatFact.fromMap(Map<String, dynamic> map) {
        return CatFact(fact: map['fact'], length: map['length']);
      }
    
      factory CatFact.fromFact(String fact) {
        return CatFact(fact: fact, length: fact.length);
      }
    
      
      String toString() => 'CatFact(fact: $fact, length: $length)';
    }
    
    void main() async {
      Dio dio = Dio();
      var url = 'https://catfact.ninja/fact';
    
      var res = await dio.get(url);
      if (res.statusCode == 200) {
        var catFact = CatFact.fromMap(res.data);
        print(catFact);
    
        var data = CatFact.fromFact(res.data['fact']);
        print(data);
      }
    }

AdviceSlip

  • https://api.adviceslip.com/advice
  • 랜덤의 조언을 받는 오픈 API
    {
    	"slip": { 
    		"id": 115, 
    		"advice": "One of the top five regrets people have is that they didn't have the courage to be their true self."
    	}
    }
  • String 데이터 받아와서 Slip 인스턴스 만들어보기
    import 'dart:convert';
    
    import 'package:dio/dio.dart';
    
    class Slip {
      int id;
      String advice;
    
      Slip({required this.id, required this.advice});
    
      factory Slip.fromMap(Map<String, dynamic> map) {
        return Slip(id: map['id'], advice: map['advice']);
      }
    
      
      toString() => advice;
    }
    
    void main() async {
      Dio dio = Dio();
      var url = 'https://api.adviceslip.com/advice';
    
      var res = await dio.get(url);
      if (res.statusCode == 200) {
        var myData = jsonDecode(res.data);
        var slipData = Slip.fromMap(myData['slip']);
        print(slipData);
      }
    }

BoredApi

  • https://www.boredapi.com/api/activity
  • 지루할 때 해야할 일을 추천해주는 오픈 API
    {
    	"activity": "Play a volleyball match with some friends",
    	"type": "social",
    	"participants": 4,
    	"price": 0,
    	"link": "",
    	"key": "4306710",
    	"accessibility": 0.3
    }
  • json 데이터 받아와서 Activity 인스턴스 만들어보기
    import 'package:dio/dio.dart';
    
    class Activity {
      String activity;
      String type;
      int participants;
      double price;
      String link;
      String key;
      double accessibility;
    
      Activity({
        required this.activity,
        required this.type,
        required this.participants,
        required this.price,
        required this.link,
        required this.key,
        required this.accessibility,
      });
    
      factory Activity.fromBoardApi(Map<String, dynamic> map) {
        return Activity(
          activity: map['activity'],
          type: map['type'],
          participants: map['participants'],
          price: map['price'] is int ? double.parse(map['price']) : map['price'],
          link: map['link'],
          key: map['key'],
          accessibility: map['accessibility'],
        );
      }
    
      
      String toString() {
        return 'Activity(activity: $activity, type: $type, participants: $participants, price: $price)';
      }
    }
    
    void main() async {
      Dio dio = Dio();
      var url = 'https://www.boredapi.com/api/activity';
    
      var res = await dio.get(url);
      if (res.statusCode == 200) {
        var activity = Activity.fromBoardApi(res.data);
        print(activity);
      }
    }
    ```![](https://velog.velcdn.com/images/gongd/post/0c4ac3b6-7122-4116-86bb-a37da75a832e/image.png)

24일차 끝.......................

profile
우와재밋다

0개의 댓글