본문 바로가기

Flutter

[Flutter] ListView 선택 selected 항목 색상 변경

보통 구현하는 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(),
    ),
  ));
}

 

[실행결과]