Search code examples
flutterriverpodriverpod-generator

How to generate providers using Riverpod generator?


With riverpod_generator, I can use:

@riverpod
int foo(FooRef ref) => 0;

which is the equivalent of:

final fooProvider = Provider((ref) => 0);

But how can I do the same thing for other providers like FutureProvider, StateProvider, etc?


Solution

  • With code generation, you can use simplify your providers declaration. There are mainly five providers and you can see how to generate the equivalent code for each of them.

    1. Provider:

      The equivalent of

      final fooProvider = Provider((ref) => 0);
      

      is

      @riverpod
      int foo(FooRef ref) => 0;
      
    2. FutureProvider:

      The equivalent of

      final fooProvider = FutureProvider((ref) async {
        return 0;
      });
      

      is

      @riverpod
      Future<int> foo(FooRef ref) async {
        return 0;
      }
      
    3. StateProvider:

      The equivalent of

      final fooProvider = StateProvider((ref) => 0);
      

      is

      @riverpod
      class Foo extends _$Foo {
        @override
        int build() => 0;
      }