[flutter] 플러터 Stepper를 사용하여 사용자가 선택한 연도와 월에 해당하는 달력을 생성하는 달력 애플리케이션을 만들어보자.

이번에는 Flutter의 Stepper 위젯을 사용하여 사용자가 선택한 연도와 월에 해당하는 달력을 생성하는 달력 애플리케이션을 만들어 보겠습니다. Flutter는 다양한 위젯들을 제공하며, Stepper 위젯을 사용하면 단계별 UI를 구성할 수 있습니다.

Step 1: 프로젝트 설정

먼저 Flutter 프로젝트를 설정하고, 필요한 라이브러리를 추가하세요. 이번 프로젝트에서는 아래와 같은 의존성을 가진 material_design_icons_flutter 패키지를 사용합니다.

dependencies:
  flutter:
    sdk: flutter
  material_design_icons_flutter: ^4.0.5955

Step 2: UI 디자인

앱의 UI는 Stepper 위젯을 사용하여 구성할 것입니다. 각 단계에는 연도와 월을 선택하는 폼이 표시됩니다.

import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

class CalendarApp extends StatefulWidget {
  @override
  _CalendarAppState createState() => _CalendarAppState();
}

class _CalendarAppState extends State<CalendarApp> {
  int _currentStep = 0;
  List<Step> _steps = [
    Step(
      title: Text('Year'),
      content: TextFormField(
        decoration: InputDecoration(labelText: 'Enter year'),
      ),
    ),
    Step(
      title: Text('Month'),
      content: TextFormField(
        decoration: InputDecoration(labelText: 'Enter month'),
      ),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar App'),
      ),
      body: Stepper(
        currentStep: _currentStep,
        onStepContinue: () {
          if (_currentStep < _steps.length - 1) {
            setState(() {
              _currentStep++;
            });
          }
        },
        onStepCancel: () {
          if (_currentStep > 0) {
            setState(() {
              _currentStep--;
            });
          }
        },
        steps: _steps,
      ),
    );
  }
}

Step 3: 사용자 입력 처리

각 단계에서 사용자가 입력한 연도와 월을 저장하고, 달력을 생성하는 로직을 추가합니다.

class _CalendarAppState extends State<CalendarApp> {
  int _currentStep = 0;
  String _selectedYear = '';
  String _selectedMonth = '';

  List<Step> _steps = [
    Step(
      title: Text('Year'),
      content: TextFormField(
        decoration: InputDecoration(labelText: 'Enter year'),
        onChanged: (value) {
          setState(() {
            _selectedYear = value;
          });
        },
      ),
    ),
    Step(
      title: Text('Month'),
      content: TextFormField(
        decoration: InputDecoration(labelText: 'Enter month'),
        onChanged: (value) {
          setState(() {
            _selectedMonth = value;
          });
        },
      ),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar App'),
      ),
      body: Stepper(
        currentStep: _currentStep,
        onStepContinue: () {
          if (_currentStep < _steps.length - 1) {
            setState(() {
              _currentStep++;
            });
          } else {
            // 달력 생성 로직 실행
            _generateCalendar();
          }
        },
        onStepCancel: () {
          if (_currentStep > 0) {
            setState(() {
              _currentStep--;
            });
          }
        },
        steps: _steps,
      ),
    );
  }

  void _generateCalendar() {
    // 선택된 연도와 월을 이용하여 달력 구성
    // 여기에 달력 생성 로직을 작성하세요.
  }
}

Step 4: 달력 생성 로직

선택된 연도와 월을 이용하여 달력을 생성하는 로직을 작성합니다. 이 예제에서는 달력을 텍스트로 출력하겠습니다.

class _CalendarAppState extends State<CalendarApp> {
  ...

  void _generateCalendar() {
    int year = int.parse(_selectedYear);
    int month = int.parse(_selectedMonth);

    DateTime startDate = DateTime(year, month, 1);
    DateTime endDate = DateTime(year, month + 1, 0);

    List<String> calendar = [];

    for (int i = 1; i <= endDate.day; i++) {
      DateTime currentDate = DateTime(year, month, i);
      String formattedDate = currentDate.toString().split(' ')[0];
      calendar.add(formattedDate);
    }

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Calendar'),
          content: Column(
            children: calendar
                .map((date) => Text(date))
                .toList(),
          ),
          actions: [
            FlatButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

결론

이제 Flutter의 Stepper를 사용하여 사용자가 선택한 연도와 월에 해당하는 달력을 생성하는 간단한 애플리케이션을 만들었습니다. Stepper를 이용하면 단계별 UI를 쉽게 구성할 수 있으며, 사용자 입력을 처리하고 결과를 출력하는 로직을 추가할 수 있습니다. 플러터의 다양한 위젯과 기능을 활용하여 더 복잡한 애플리케이션을 만들어보세요.