1. 기존방법
class Player {
late final String name;
late int xp;
// 생성자
Player(String name, int xp) {
this.name = name;
this.xp = xp;
}
.
.
.
2. 새롭게 학습한 방법
class Player {
final String name;
int xp;
Player(this.name, this.xp); // 생성자
void sayHello() {
print('안녕하세요 저는 $name에요');
}
}
class Player {
final String name;
int xp;
Player({required this.name, required this.xp}); // 생성자
void sayHello() {
print('안녕하세요 저는 $name에요');
}
}
void main() {
var player = Player(
name : '나루',
xp : 10000
);
player.sayHello();
}
class Player {
final String name;
int xp, age;
String team;
Player({
required this.name,
required this.xp,
required this.age,
required this.team,
});
Player.createYoki({required String name, required int age})
: this.name = name,
this.age = age,
this.xp = 0,
this.team = 'Yoki';
Player.createShiba(String name, int age)
: this.name = name,
this.age = age,
this.xp = 100,
this.team = 'Shiba';
void sayHello() {
print('안녕하세요 저는 $name에요');
}
}
void main() {
var player = Player(
name: '나루',
xp: 10000,
age: 8,
team: 'family',
);
// named constructor
var playerYoki = Player.createYoki(
name: '나루',
age: 8,
);
// positional constructor
var playerShiba = Player.createShiba(
'미소',
6,
);
player.sayHello();
print('playerYoki Info');
print(playerYoki.name);
print(playerYoki.xp);
print(playerYoki.age);
print(playerYoki.team);
print('playerShiba Info');
print(playerShiba.name);
print(playerShiba.xp);
print(playerShiba.age);
print(playerShiba.team);
}
class Player {
final String name;
int xp;
String team;
Player.fromJson(Map<String, dynamic> playerJson)
: this.name = playerJson['name'],
this.xp = playerJson['xp'],
this.team = playerJson['team'];
void sayHello() {
print('안녕하세요 저는 $name에요');
}
}
void main() {
var apiData = [
{
'name': '나루',
'team': 'Yoki',
'xp': 0,
},
{
'name': '미소',
'team': 'Shiba',
'xp': 0,
},
{
'name': '하루',
'team': 'DachsHund',
'xp': 0,
}
];
apiData.forEach((playerJson) {
var player = Player.fromJson(playerJson);
player.sayHello();
});
}