본문으로 바로가기
  1. Home
  2. Flutter/Package
  3. Flutter Riverpod 상태관리 (2) - 시작하기

Flutter Riverpod 상태관리 (2) - 시작하기

· 댓글개 · Dev_Whale

시작하기

온라인에서 Rivderpod 사용하기

Riverpod을 체험해 보시려면 Dartpad에서 온라인으로 체험해 보세요.

패키지 설치하기

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

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

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

name: my_app_name
environment:
  sdk: ">=2.17.0 <3.0.0"
  flutter: ">=3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: ^2.3.6
  riverpod_annotation: ^2.1.1

dev_dependencies:
  build_runner:
  custom_lint:
  riverpod_generator: ^2.2.3
  riverpod_lint: ^1.3.2

그런 다음 "Flutter Pub get"이 포함된 패키지를 설치합니다.

 

"dart run build_runner watch"로 code-generator를 실행합니다.

 

여기까지입니다. 앱에 Riverpod을 추가했습니다!

riverpod_lint/custom_lint 활성화

Rivderpod은 더 나은 코드를 작성하는 데 도움주고 커스텀 리팩토링 옵션을 제공하는 riverpod_lint 패키지를 함께 제공합니다.

 

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

 

riverpod_lint를 사용 설정하려면 pubspec.yaml 와 같은 폴더에 analysis_options.yaml을 추가하고 다음을 포함해야 합니다:

analysis_options.yaml - 파일 이름
// 아래의 코드
analyzer:
  plugins:
    - custom_lint

이제 작성한 코드가 있다면 IDE에서 Riverpod을 사용할 때 실수가 경고로 표시됩니다.

경고 및 리팩터링의 전체 목록을 보려면 riverpod_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 할 수 있습니다.
@riverpod
String helloWorld(HelloWorldRef ref) {
  return 'Hello world';
}

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

// Riverpod에 의해 노출되는 StatelessWidget 대신 ConsumerWidget을 추가하세요
class MyApp extends ConsumerWidget {
  @override
  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와 VS Code를 사용하는 경우 Flutter Riverpod Snippets을 사용하는 것이 좋습니다.

Flutter와 안드로이드 스튜디오 또는 IntelliJ를 사용하는 경우, Flutter Riverpod Snippets 사용을 고려해 보세요.

💬 댓글 개
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

이모티콘을 클릭하면 댓글창에 입력됩니다.