[flutter] Flutter Riverpod에서 간편 계산기 앱 만들기

Flutter는 Google에서 개발한 모바일 앱 개발 프레임워크로 Riverpod이라는 상태관리 라이브러리를 사용하여 간단한 계산기 앱을 만들 수 있습니다. Riverpod은 Provider를 기반으로 하며 상태 관리를 더욱 효율적으로 할 수 있게 해줍니다. 이번 글에서는 Riverpod을 사용하여 간단한 계산기 앱을 만드는 방법에 대해 알아보겠습니다.

목표

이번 프로젝트의 목표는 다음과 같습니다.

프로젝트 구성

프로젝트를 시작하기 전에 Flutter 프로젝트를 생성해야 합니다. Flutter 프로젝트를 생성한 후 pubspec.yaml 파일에 다음과 같이 Riverpod을 추가해줍니다.

dependencies:
  flutter:
    sdk: flutter
  riverpod: ^1.0.3

이제 Flutter 프로젝트에 Riverpod 패키지를 추가했으니, 이제 간단한 계산기 앱을 만들어 보겠습니다.

계산기 앱 만들기

1. 상태 정의하기

먼저, 계산기 앱에서 사용할 상태를 정의해야 합니다. 다음은 계산기 앱에 필요한 상태를 정의하는 예시입니다.

final calculatorProvider = ChangeNotifierProvider((ref) => Calculator());

2. UI 구성하기

다음으로 사용자 인터페이스를 구성해야 합니다. 사용자가 숫자를 입력하고 계산 버튼을 누를 수 있는 화면을 구성합니다.

class CalculatorScreen extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final calculator = watch(calculatorProvider);
    
    return Scaffold(
      appBar: AppBar(
        title: Text('간편 계산기'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '결과: ${calculator.result}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                RaisedButton(
                  onPressed: () => calculator.add(1),
                  child: Text('+ 1'),
                ),
                RaisedButton(
                  onPressed: () => calculator.subtract(1),
                  child: Text('- 1'),
                ),
              ],
            ),
            SizedBox(height: 20),
            RaisedButton(
              onPressed: () => calculator.reset(),
              child: Text('초기화'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 비즈니스 로직 구현하기

마지막으로, 비즈니스 로직을 구현해야 합니다. Calculator 클래스를 만들어 덧셈, 뺄셈, 초기화 등의 기능을 구현합니다.

class Calculator extends ChangeNotifier {
  int _result = 0;

  int get result => _result;

  void add(int value) {
    _result += value;
    notifyListeners();
  }

  void subtract(int value) {
    _result -= value;
    notifyListeners();
  }

  void reset() {
    _result = 0;
    notifyListeners();
  }
}

결론

이제 Riverpod을 사용하여 간단한 계산기 앱을 만들었습니다. 이 예제를 통해 Riverpod을 활용하여 Flutter 앱의 상태 관리를 효율적으로 할 수 있음을 알 수 있습니다. 상태 관리가 복잡해질수록, Riverpod은 더욱 가독성 있고 유지보수가 용이한 코드를 작성할 수 있도록 도와줍니다.

더 많은 기능을 추가하여 풍부하고 유용한 계산기 앱을 만들어보세요!

참고 자료: