[flutter] AspectRatio를 사용하여 이미지 슬라이더 만들기
이미지 슬라이더를 만들 때, AspectRatio
위젯을 사용하여 이미지의 측면비를 유지하면서 화면에 효과적으로 표시할 수 있습니다. 이제 AspectRatio
위젯을 사용하여 간단한 이미지 슬라이더를 구현하는 방법에 대해 알아보겠습니다.
1. 이미지 슬라이더 위젯 만들기
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ImageSlider(),
);
}
}
class ImageSlider extends StatelessWidget {
final List<String> imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg',
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Slider'),
),
body: PageView.builder(
itemCount: imageUrls.length,
itemBuilder: (context, index) {
return AspectRatio(
aspectRatio: 16 / 9,
child: Image.network(
imageUrls[index],
fit: BoxFit.cover,
),
);
},
),
);
}
}
위의 예제는 AspectRatio
위젯을 이용하여 이미지 슬라이더를 만드는 방법을 보여줍니다.
2. 설명
AspectRatio
위젯은 자식 위젯의 가로 세로 비율을 유지하도록 도와줍니다. 여기서는 16:9의 가로 세로 비율을 갖는 이미지를 표시하기 위해aspectRatio
를 16/9로 설정했습니다.PageView.builder
를 사용하여 이미지를 슬라이드할 수 있는 화면을 만들었습니다.PageView.builder
는 주어진 아이템을 빌드하고 스크롤이 가능한 페이지 레이아웃을 만듭니다.
이것으로 AspectRatio
를 이용하여 간단한 이미지 슬라이더를 만드는 방법에 대해 알아보았습니다. AspectRatio를 활용하여 콘텐츠의 가로 세로 비율을 조정하는 데 활용할 수 있습니다.
참고자료: Flutter AspectRatio class