Flutter Riverpod:如何在家庭中传递多个参数?

Flutter Riverpod: how to pass multiple arguments in family?

我可以在 Riverpod ChangeNotifierProvider 系列中将一个参数与 ProviderScope 一起传递。但是我需要通过one/multiplearguments/dependencies以上。 例如,我必须传递上下文以通过 context.read(provider) 和来自 UI 小部件的依赖项访问其他提供者的值,可能还有更多。

此处示例:

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();
  }
}

如果您想在创建 Provider 时将多个值传递给它,您可以使用带有自定义类型的 family 修饰符。

例如,在这种情况下,您可能希望将 String 值替换为 Person 值:

final multipleGreetingProvider = Provider.family<String, Person>(
  (_, person) {
    return "Hello, ${person.name} ${person.surname}!";
  },
);

您现在可以在创建 Provider 时将 Person 值传递给它:

// prints "Hello, Paul Halliday!"
sayHello(WidgetRef ref) {
  ref.read(
    multipleGreetingProvider(
      Person('Paul', 'Halliday'),
    )
  );
}

这个可以无限延长。如果你现在有多个类你想传入,你可以把它组合成一个逻辑单元。

例如,这可能看起来像:

class Household {
  final List<Person> members;
  final int rooms;

  Household(this.members, this.rooms);
}

final householdProvider = Provider.family<String, Household>(
  (_, household) {
    return "Household has ${household.rooms} rooms and ${household.members.length} members.";
  },
);

// prints "Household has 3 rooms and 1 members."
householdData(WidgetRef ref) {
  ref.read(householdProvider(
    Household(
      [
        Person('Paul', 'Halliday'),
      ],
      3,
    ),
  ));
}

这显示了如何解决必须使用 family.

将多个值传入 Provider 的问题

ref.