[flutter] 플러터 Stepper를 사용하여 사용자가 선택한 숫자 자릿수로 로또 번호를 생성하는 로또 번호 생성기 애플리케이션을 만들어보자.

플러터(Flutter) Stepper를 사용하여 사용자가 선택한 숫자 자릿수에 따라 로또 번호를 생성하는 로또 번호 생성기 애플리케이션을 만들어보겠습니다. 이 애플리케이션은 사용자가 원하는 자릿수를 선택하고, 해당 자릿수 만큼의 랜덤한 로또 번호를 생성하여 화면에 보여줍니다.

Stepper 위젯 설정

먼저, 애플리케이션의 기본 구조를 설정하기 위해 MaterialApp과 Scaffold 위젯을 사용합니다. Scaffold 위젯 안에는 Stepper 위젯을 배치하여 사용자가 자릿수를 선택할 수 있도록 합니다.

import 'package:flutter/material.dart';

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

class LottoGeneratorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lotto Generator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LottoGeneratorScreen(),
    );
  }
}

class LottoGeneratorScreen extends StatefulWidget {
  @override
  _LottoGeneratorScreenState createState() => _LottoGeneratorScreenState();
}

class _LottoGeneratorScreenState extends State<LottoGeneratorScreen> {
  int _currentStep = 0;
  int _selectedDigits = 0;

  List<Step> _steps = [
    Step(
      title: Text('Select Digits'),
      content: Text('Choose the number of digits for the lotto number'),
      isActive: true,
    ),
    // more steps can be added here
  ];

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

위 코드는 MaterialApp을 사용하여 애플리케이션의 기본 구조를 설정하고, Scaffold를 사용하여 앱바와 Stepper 위젯을 배치한 기본 화면을 생성합니다. 현재 선택된 스텝을 추적하기 위해 _currentStep 변수를 사용하고, 로또 번호의 자릿수를 저장하기 위해 _selectedDigits 변수를 사용합니다.

Stepper 위젯에는 currentStep 속성에 현재 선택된 스텝을, steps 속성에 각 스텝의 정보를 제공합니다. onStepContinue 콜백은 다음 스텝으로 이동하고 _currentStep을 업데이트합니다. onStepCancel 콜백은 이전 스텝으로 이동하고 _currentStep을 업데이트합니다. onStepTapped 콜백은 특정 스텝을 탭한 경우 해당 스텝으로 이동하고 _currentStep을 업데이트합니다.

스텝 추가 및 로또 번호 생성

이제 사용자가 선택한 자릿수에 따라 로또 번호를 생성하는 스텝을 추가하고, 실제 로또 번호를 생성하는 기능을 구현해보겠습니다.

class _LottoGeneratorScreenState extends State<LottoGeneratorScreen> {
  ...

  List<Step> _steps = [
    Step(
      title: Text('Select Digits'),
      content: Text('Choose the number of digits for the lotto number'),
      isActive: true,
    ),
    Step(
      title: Text('Generate Numbers'),
      content: Column(
        children: [
          Text('Selected Digits: $_selectedDigits'),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _generateLottoNumbers,
            child: Text('Generate'),
          ),
          SizedBox(height: 16),
          Text('Lotto Numbers:'),
          Text(
            _lottoNumbers.join(' '),
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
        ],
      ),
      isActive: _currentStep == 1,
    ),
  ];

  List<int> _lottoNumbers = [];

  void _generateLottoNumbers() {
    setState(() {
      _lottoNumbers = List.generate(
        6,
        (_) => Random().nextInt(pow(10, _selectedDigits)),
      );
    });
  }

  ...
}

위 코드에서는 _steps 리스트에 새로운 스텝을 추가하고, onStepContinue 콜백을 _currentStep이 1인 경우에만 _generateLottoNumbers 함수를 호출하여 로또 번호를 생성하고 _lottoNumbers 변수에 할당합니다.

_generateLottoNumbers 함수는 List.generate 메서드를 사용하여 입력된 _selectedDigits값에 따라 1부터 _selectedDigits 자릿수까지의 랜덤한 로또 번호 6개를 생성합니다.

애플리케이션 결과

이제 애플리케이션을 실행해보면, 첫 번째 스텝에서 자릿수를 선택할 수 있고, 두 번째 스텝에서 선택된 자릿수에 따라 생성된 로또 번호가 화면에 나타나게 됩니다.

Lotto Generator

결론

위의 코드를 참고하여 플러터 Stepper를 이용한 로또 번호 생성기 애플리케이션을 개발할 수 있습니다. Stepper 위젯을 사용하여 다단계 프로세스를 쉽게 구현할 수 있고, setState() 메소드를 호출하여 화면을 업데이트하는 방식으로 사용자 인터랙션을 처리할 수 있습니다.