1

I'm using Riverpod and Riverpod generator (great packages by the way), and I was wondering is there a way to pass a label AND an initial value to a generated Provider? There are lots of times where I want the Provider to hold a large Dart object/class, but I want to find that Provider using just a string. For instance, say I have a large dart class called Patient, and each patient has a unique ID.

@riverpod
class PatientProvider extends _$PatientProvider {
  @override
  Patient build(Patient patient) => patient;
}

That one works, but then if I want to access that Provider I have to pass in the patient each time, which kind of defeats the purpose. I could do something like this:

@riverpod
class PatientProvider extends _$PatientProvider {
  @override
  Patient build(String id) => Patient();

  void newValue(Patient patient) {
    state = patient;
  }
}

But that requires me to initialize the provider, and then set a new value. Not a huge lift and certainly doable, but what I'd really like is something like this:

@riverpod
class PatientProvider extends _$PatientProvider {
  @override
  Patient build({required String id, Patient? Patient) => patient ?? Patient();
}

So then for the last one I could use:

ref.read(patientProvider(id));

And it would return the value of the Patient.Does anyone know if there's a way to do this?

Grey
  • 331
  • 3
  • 11

0 Answers0