보통 구현하는 ListView 는 리스트 항목이 Pressed 될 때 바로 이벤트가 발생되지만
일부 경우 User에게 항목 선택 상태를 우선 보여주고 이벤트를 실행 할지 말지 선택하는 시간을 줘야하는 경우가 있습니다.
또한 대부분 ListView 에서 리스트는 class 함수로 따로 리턴해주기 때문에 분리된 코드로 구성했습니다.
GPT 코드라서 뭔가 어설프지만 작동은 잘되네요. ㅎㅎ
import 'package:flutter/material.dart';
class AdTopBannerListWidget extends StatefulWidget {
const AdTopBannerListWidget({Key? key}) : super(key: key);
@override
State<AdTopBannerListWidget> createState() => _AdTopBannerListWidgetState();
}
class _AdTopBannerListWidgetState extends State<AdTopBannerListWidget> {
late List<bool> _isSelectedList;
@override
void initState() {
super.initState();
_isSelectedList = List.generate(10, (index) => false);
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
// Reset the previous selection
for (int i = 0; i < _isSelectedList.length; i++) {
if (i != index) {
_isSelectedList[i] = false;
}
}
// Toggle the current selection
_isSelectedList[index] = !_isSelectedList[index];
});
},
child: AdTopBannerItem(
isSelected: _isSelectedList[index],
index: index,
),
);
},
);
}
}
class AdTopBannerItem extends StatelessWidget {
final bool isSelected;
final int index;
const AdTopBannerItem({
Key? key,
required this.isSelected,
required this.index,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: 70,
padding: const EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: isSelected ? Colors.purple : Colors.white,
border: const Border(
bottom: BorderSide(
width: 1,
color: Colors.purple,
),
),
),
child: Text('Item $index'),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('AdTopBannerListWidget Example'),
),
body: AdTopBannerListWidget(),
),
));
}
[실행결과]
'Flutter' 카테고리의 다른 글
[Flutter] Flutter Doctor 에러 처리 모음 (안드로이드스튜디오) (0) | 2023.07.17 |
---|---|
[Flutter] 드롭다운 버튼(DropdownButton) (0) | 2023.06.05 |
[Flutter] 플러터 Color 컬러 Class 분할 및 Style 변수 적용 관리 (0) | 2023.03.25 |
[Flutter] 플러터 빌드 후 충돌되는 Json 모듈 삭제 방법 (0) | 2023.03.20 |
[Flutter] 플러터 Placeholder (자리표시자) 엑스박스 (0) | 2023.03.17 |