dart: often used fromJSON function

Darcy Daeseok YU ·2022년 12월 2일
0

Flutter에서 자주 사용되는 클래스 패턴 JSON to Instance

class Player {
  final String name;
  String team;
  int xp;

  Player.fromJSON(Map<String, dynamic> playerJson)
      : name = playerJson['name'],
        team = playerJson['team'],
        xp = playerJson['xp'];

  void sayHello() {
    print("Hi, I am $name in $team team");
  }
}

void main() {
  var apiData = [
    {
      'name': 'Sonny',
      'team': 'red',
      'xp': 0,
    },
    {
      'name': 'Sonny1',
      'team': 'blue',
      'xp': 0,
    },
    {
      'name': 'Sonny2',
      'team': 'yellow',
      'xp': 0,
    },
  ];

  apiData.forEach((player) {
    var newIns = Player.fromJSON(player);

    newIns.sayHello();
  });
}
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글