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?
2
Answers
You can use it like that
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:
As you can see, "ref" by default is accessible in your class. So you don’t need to manually pass it.