🦍

riverpod_generatorを使ってみた

2023/10/08に公開

riverpod_generator

riverpodのxxxProviderのようなproviderを自動で作成してくれるパッケージ
https://pub.dev/packages/riverpod_generator

今までの場合

final counterProvider =
    StateNotifierProvider.autoDispose<Counter, int>((ref) => Counter());

class Counter extends StateNotifier<int> {
  Counter() : super(0);

  void increment() => state++;
}

riverpod_generatorを使用した場合

part 'counter_notifier.g.dart';


class Counter extends _$Counter {
  
  int build() => 0;

  void increment() => state++;
}

freezedのようにpart 'counter_notifier.g.dart'を記述し、Notifierクラスの上に、@riverpodを加える。

あとは、flutter pub run build_runner watchを実行

以下のcounter_notifier.g.dartファイルが生成される。

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'counter_notifier.dart';

// **************************************************************************
// RiverpodGenerator
// **************************************************************************

// ignore_for_file: avoid_private_typedef_functions, non_constant_identifier_names, subtype_of_sealed_class, invalid_use_of_internal_member, unused_element, constant_identifier_names, unnecessary_raw_strings, library_private_types_in_public_api

/// Copied from Dart SDK
class _SystemHash {
  _SystemHash._();

  static int combine(int hash, int value) {
    // ignore: parameter_assignments
    hash = 0x1fffffff & (hash + value);
    // ignore: parameter_assignments
    hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
    return hash ^ (hash >> 6);
  }

  static int finish(int hash) {
    // ignore: parameter_assignments
    hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
    // ignore: parameter_assignments
    hash = hash ^ (hash >> 11);
    return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
  }
}

String _$CounterHash() => r'4243b34530f53accfd9014a9f0e316fe304ada3e';

/// See also [Counter].
final counterProvider = AutoDisposeNotifierProvider<Counter, int>(
  Counter.new,
  name: r'counterProvider',
  debugGetCreateSourceHash:
      const bool.fromEnvironment('dart.vm.product') ? null : _$CounterHash,
);
typedef CounterRef = AutoDisposeNotifierProviderRef<int>;

abstract class _$Counter extends AutoDisposeNotifier<int> {
  
  int build();
}

counterアプリ使ったサンプル

https://github.com/NoriakiSakata/riverpod_generator_test

Discussion