주요 콘텐츠로 건너뛰기

시작하기

온라인에서 Riverpod 체험해보기

Riverpod을 체험해보려면 DartpadZapp에서 온라인으로 사용해보세요:

패키지 설치하기

설치하려는 패키지가 정해지면, 아래와 같이 한 줄로 앱에 종속성을 추가합니다:

flutter pub add flutter_riverpod
flutter pub add riverpod_annotation
flutter pub add dev:riverpod_generator
flutter pub add dev:build_runner
flutter pub add dev:custom_lint
flutter pub add dev:riverpod_lint

또는, pubspec.yaml 내에서 앱에 종속성을 수동으로 추가할 수 있습니다:

pubspec.yaml
name: my_app_name
environment:
sdk: ">=3.0.0 <4.0.0"
flutter: ">=3.0.0"

dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^2.5.1
riverpod_annotation: ^2.3.5

dev_dependencies:
build_runner:
custom_lint:
riverpod_generator: ^2.4.2
riverpod_lint: ^2.3.12

그리고, flutter pub get으로 패키지를 설치합니다.

이제 코드 생성기를 실행할 수 있습니다. flutter pub run build_runner watch.

이게 전부입니다. 당신의 앱에 Riverpod을 추가했습니다!

riverpod_lint/custom_lint 활성화하기

Riverpod은 선택사항으로 riverpod_lint 패키지를 제공합니다. 이 패키지는 더 좋은 코드를 작성하는데 도움이 되는 린트 규칙과 사용자 정의 리팩토링 옵션을 제공합니다.

이전 단계를 수행했다면 이미 패키지가 설치되어 있지만, 활성화하려면 별도의 단계가 필요합니다.

riverpod_lint를 활성화하려면, 당신의 pubspec.yaml옆에 analysis_options.yaml을 추가하고 다음을 포함해야 합니다:

analysis_options.yaml
analyzer:
plugins:
- custom_lint

이제 코드베이스에서 Riverpod을 사용할 때 당신이 실수한 경우, IDE에서 경고가 보이게 됩니다.

전체 경고와 리팩토링 목록을 보려면 riverpod_lint 페이지를 참고하세요.

노트

이 경고는 dart analyze 명령에서는 표시되지 않습니다. CI/터미널에서 이 경고를 확인하려면 다음을 실행하세요:

dart run custom_lint

사용 예시: Hello world

이제 Riverpod를 설치했으니 사용해볼 수 있습니다.

다음 스니펫은 새로운 종속성을 사용하여 "Hello world"를 만드는 방법을 보여줍니다:

lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'main.g.dart';

// 값을 저장할 "provider"를 생성합니다(여기서는 "Hello world").
// provider를 사용하면 노출된 값을 모의(mock)//재정의(override)할 수 있습니다.

String helloWorld(HelloWorldRef ref) {
return 'Hello world';
}

void main() {
runApp(
// 위젯이 providers를 읽을 수 있게 하려면 전체 애플리케이션을 "ProviderScope" 위젯으로 감싸야 합니다.
// 여기에 providers의 상태가 저장됩니다.
ProviderScope(
child: MyApp(),
),
);
}

// Riverpod에 의해 노출되는 StatelessWidget 대신 ConsumerWidget을 확장합니다.
class MyApp extends ConsumerWidget {

Widget build(BuildContext context, WidgetRef ref) {
final String value = ref.watch(helloWorldProvider);

return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text(value),
),
),
);
}
}

이제 flutter run으로 앱을 시작할 수 있습니다. 이렇게 하면 기기에 "Hello world"가 표시됩니다.

더 나아가기: 코드 스니펫 설치하기

FlutterVS Code를 사용하고 있다면 Flutter Riverpod Snippets를 사용해보세요.

FlutterAndroid Studio 또는 IntelliJ를 사용하고 있다면 Flutter Riverpod Snippets를 사용해보세요.

img

다음 단계 선택

몇 가지 기본 개념 알아보기:

쿡북(Cookbook) 따라하기: