Prox
Prox

Reputation: 63

Flutter: Riverpod - Illegal use of Ref within a provider

I am currently creating an app using Flutter and Riverpod. I ran into a problem where I had to call another StateNotifier provider in a StateNotifier provider (I don't know if that's already a bad style). While searching for a solution I came across the following solution with a code example:

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

class YourProvider extends ChangeNotifier {
  Ref ref;

  YourProvider(this.ref) : super();

  callOtherProviderFromThisProvider() {
    ref.read(otherProvider).someMethodINeedToTrigger();
  }
}

final yourProvider = ChangeNotifierProvider<YourProvider>(
    (ref) => YourProvider(ref));

This solution solved my problems, but it feels wrong and I am afraid that it might be bad style.

Is this a solution that can be used in this context or should this be solved differently?

Upvotes: 3

Views: 2245

Answers (2)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277527

Passing the "ref" object to your ChangeNotifier is perfectly fine, and in fact, the recommended way.

I would add that you would not need to do this if you were to use riverpod_generator, which is an official syntax upgrade for Riverpod relying on code generation.

Using it, the equivalent to your sample would be:

@riverpod
class YourNotifier extends _$YourNotifier {
  YourState build() {/* initialize your state */}

  void callOtherProviderFromThisProvider() {
    // "ref" is naturally a property of your class
    ref.read(otherProvider).someMethodINeedToTrigger();
  }
}

As you can see, "ref" by default is accessible in your class. So you don't need to manually pass it.

Upvotes: 7

Tanjim ahmed
Tanjim ahmed

Reputation: 599

You can use it like that

final yourProvider = ChangeNotifierProvider<YourProvider>((ref) => YourProvider(ref.read(otherProvider)));

class YourProvider extends ChangeNotifier {
  OtherProvider otherProvider;

  YourProvider(this.otherProvider) : super();

  callOtherProviderFromThisProvider() {
    otherProvider.someMethodINeedToTrigger();
  }
}

Upvotes: 1

Related Questions