Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Riverpod: how to pass multiple arguments in family?

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();
  }
}
like image 779
Golam Sarwar Shakil Avatar asked Oct 20 '25 08:10

Golam Sarwar Shakil


1 Answers

You can use typedef with Dart 3. It offers easy and simple use with the family parameter.

typedef Parameters= ({String type, int maxPrice});

Then you can use provider like this

final providerName= FutureProvider.family<Activity, Parameters>((ref, arguments) async {
    .......
});

It's pretty simple now

Use it like so:

providerName((type: "a", maxPrice: 1));

Notice the double parentheses.

like image 133
Şafak Bahçe Avatar answered Oct 23 '25 06:10

Şafak Bahçe