I can pass one argument along with ProviderScope in Riverpod ChangeNotifierProvider family. But I need to pass more than one/multiple arguments/dependencies. For example I have to pass context to access other providers value via context.read(provider) and dependencies from UI widget, may be some more also.
Example here:
final restaurantProvider = ChangeNotifierProvider.family(
(ref, BuildContext context, Restaurant? restaurant) => RestaurantNotifier(
context: context,
restaurant: restaurant,
),
);
class RestaurantNotifier extends ChangeNotifier {
RestaurantNotifier(
{required BuildContext context, required Restaurant? restaurant}) {
getPlaceMark(restaurant);
checkIsSaved(context, restaurant!.id);
}
getPlaceMark(Restaurant? restaurant) async {
if (restaurant!.latitude != null && restaurant.longitude != null) {
List<Placemark> placemarkData = await LocationHelper.getPlaceMark(
lat: double.tryParse(restaurant.latitude!)!,
long: double.tryParse(restaurant.longitude!)!,
);
placemark = placemarkData[0];
}
}
checkIsSaved(BuildContext context, int? id) {
final savedRestaurantsId = context.read(savedRestaurantsIdProvider.state);
isSaved = savedRestaurantsId.contains(id);
notifyListeners();
}
}
If you want to pass multiple values into the
Provider
when you create it, you can use thefamily
modifier with a custom type.For example, in this instance, you may want to replace the
String
value with aPerson
value:You can now pass a
Person
value into theProvider
when you create it:This can be extended infinitely. If you now have multiple classes you'd like to pass in, you can combine this into a logical unit.
For example, this may look like:
This shows how to get around the problem of having to pass in multiple values into the
Provider
usingfamily
.ref.