[flutter] DataTable에서 행의 배경색 변경하는 방법

Flutter의 DataTable은 테이블 형식으로 데이터를 표시하는 데 사용됩니다. 사용자 정의 형식으로 행을 표시하고 싶은 경우, 특히 각 행의 배경색을 변경하고 싶은 경우에는 어떻게 해야 하는지 알아보겠습니다.

1. 행의 배경색 변경하기

DataRow(
  color: MaterialStateColor.resolveWith((Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
      return Theme.of(context).colorScheme.primary.withOpacity(0.08);
    }
    if (index % 2 == 0) {
      return Colors.grey.withOpacity(0.3);
    }
    return null;  // Use default value for other states and odd rows
  }),
  cells: [ // cells... ]
)

위 코드에서 DataRow 위젯의 color 속성을 사용하여 특정 상태에 따라 행의 배경색을 동적으로 변경할 수 있습니다. MaterialStateColor.resolveWith 메서드를 사용하여 각 상태에 따라 색상을 반환할 수 있습니다.

이 예시에서는 선택된 상태일 때의 배경색, 인덱스가 짝수일 때의 배경색, 그리고 기본 색상을 정의하였습니다.

2. 전체 코드 예시

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: DataTable(
          columns: const [
            DataColumn(label: Text('Name')),
            DataColumn(label: Text('Age')),
          ],
          rows: List<DataRow>.generate(
            5, 
            (index) => DataRow(
              color: MaterialStateColor.resolveWith((Set<MaterialState> states) {
                if (states.contains(MaterialState.selected)) {
                  return Theme.of(context).colorScheme.primary.withOpacity(0.08);
                }
                if (index % 2 == 0) {
                  return Colors.grey.withOpacity(0.3);
                }
                return null;  // Use default value for other states and odd rows
              }),
              cells: <DataCell>[
                DataCell(Text('Person ${index + 1}')),
                DataCell(Text((20 + index).toString())),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

위 예시는 간단한 DataTable을 생성하고, 각 행의 배경색을 동적으로 변경하는 방법을 보여줍니다.

행의 배경색을 변경하는 데 사용된 MaterialStateColor.resolveWith 메서드는 선택된 상태 또는 특정 조건을 만족하는 상태일 때 적절한 색상을 반환하는 매우 유용한 기능입니다.

이제부터는 DataTable을 사용할 때 행의 배경색을 쉽게 변경할 수 있을 것입니다. 만약 도움이 필요하거나 추가 질문이 있다면 언제든지 물어주세요!