Working with subscriptions in your Flutter app using the RevenueCat package is great, but sometimes you need little helpers to make things smoother. Here are some useful extension methods that can save you time and make your code cleaner.
Get subscription product period as Duration
Understanding the exact duration of a subscription period can be tricky with different formats like P1W, P1M, etc. This extension converts the subscriptionPeriod
property into a standard Dart Duration
object.
duration get duration => switch(revenueCatPackage.storeProduct.subscriptionPeriod) {
'P1W' => const Duration(days: 7),
'P1M' => const Duration(days: 30),
'P3M' => const Duration(days: 90),
'P6M' => const Duration(days: 180),
'P1Y' => const Duration(days: 365),
_ => Duration.zero,
};
Get the number of trial days for a product
If your product offers a free trial, you'll often need to know how many days it lasts. This method checks the introductory price and calculates the total trial days.
int? get trialDays {
final introductory = revenueCatPackage.storeProduct.introductoryPrice;
if (introductory == null) {
return null;
}
if (introductory.price == 0) {
final unit = introductory.periodUnit;
switch (unit) {
case PeriodUnit.day:
return introductory.periodNumberOfUnits;
case PeriodUnit.week:
return introductory.periodNumberOfUnits * 7;
case PeriodUnit.month:
return introductory.periodNumberOfUnits * 30;
case PeriodUnit.year:
return introductory.periodNumberOfUnits * 365;
default:
return null;
}
}
return null;
}
Get the list of features from the RevenueCat metadata according to user language
Product metadata is a handy place to store information like key features. This extension helps you fetch a list of features stored in the metadata, specifically for the user's current language.
List<String>? get features {
final locale = LocaleSettings.currentLocale.languageCode;
if (revenueCatOffer.metadata[locale] == null) {
return null;
}
final data = revenueCatOffer.metadata[locale] as Map<Object?, Object?>;
final featuersObj = data["features"]! as List<Object?>;
return featuersObj.map((e) => e! as String).toList();
}
These simple extensions can help you manage common tasks with RevenueCat data more effectively in your Flutter app.