Flutter江荚:如何在family中传递多个参数?

4dc9hkyq  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(188)

我可以在Riverpod ChangeNotifierProvider家族中传递一个参数和ProviderScope。但我需要传递多个参数/依赖项。例如,我必须通过www.example.com(提供者)传递上下文以访问其他提供者值,并且从UI小部件传递依赖项,也可能更多。context.read(provider) and dependencies from UI widget, may be some more also.
示例如下:

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

wlp8pajw1#

如果您想在创建Provider时将多个值传递给它,则可以将family修饰符与自定义类型一起使用。
例如,在此示例中,您可能希望将String值替换为Person值:

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

现在,您可以在创建Provider时将Person值传递到Provider

// 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 .

nfs0ujit

nfs0ujit2#

这是提供多个参数的另一种方式。使用List<dynamic>>

final restaurantProvider = FutureProvider.autoDispose
.family<RecordModel, List<dynamic>>(
    (ref, args) => ref.read(rsProvider).load(args[0], args[1]));

相关问题