중복되는 코드를 별도의 Stateless Widget으로 분리
분리된 UI에 변경되어야 하는 값을 생성자를 통해 받도록 수정
class ImageData extends StatelessWidget {
final String name;
const ImageData(this.name, {Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Row (
children: [
Image.asset(
'assets/pic.jpg',
width: 100,
height: 100,
),
Text(
name,
style: TextStyle(fontSize: 100),
),
],
);
}
}
전달할 값이 많아지면 추가하면 된다.
class ImageData extends StatelessWidget {
final String name;
final String imageUrl;
const ImageData(this.name, this.imageUrl, {Key? key})
: super(key: key);
Widget build(BuildContext context) {
return Row (
children: [
Image.asset(
imageUrl,
width: 100,
height: 100,
),
Text(
name,
style: TextStyle(fontSize: 100),
),
],
);
}
}
가독성이나 편의성을 위해 Named Parameter 고려
child: ImageData(
name: items[index],
imageUrl: 'http://',
),
const ImageData({Key? key, this.name, this.imageUrl})
: super(key: key);
넘길 값이 너무 많을 때는 Map으로 넘기는 것 가능
child: ImageData(
data: {
'name': '홍길동',
'imageUrl': 'https://',
}
),
class ImageData extends StatelessWidget {
final Map<String, dynamic> data;
const ImageData({Key? key, this.data}) : super(key: key);
Widget build(BuildContext context) {
return Row (
children: [
Image.asset(
data['imageUrl'],
width: 100,
height: 100,
),
Text(
data['name'],
style: TextStyle(fontSize: 100),
),
],
);
}
}
Map은 타입에 안전하지 않기 때문에 모델 클래스로 변경하는 것 고려
class Image {
final String previewUrl;
final String tags;
Image({
required this.previewUrl,
required this.tags,
});
}
child: ImageData(
profile: Profile(
name: '홍길동',
imageUrl: 'https://',
)
),
class ImageData extends StatelessWidget {
final Profile profile;
const ImageData({Key? key, this.profile}) : super(key: key);
Widget build(BuildContext context) {
return Row (
children: [
Image.asset(
profile.imageUrl,
width: 100,
height: 100,
),
Text(
profile.name,
style: TextStyle(fontSize: 100),
),
],
);
}
}
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
Iterable : https://papabee.tistory.com/43