Flutter应用内购买优惠管理插件in_app_purchase_offers的使用

Flutter应用内购买优惠管理插件in_app_purchase_offers的使用

插件概述

in_app_purchase_offers 是一个用于管理 Flutter 应用内购买优惠的插件。通过该插件,开发者可以轻松地查询和展示产品及其促销优惠信息。

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 in_app_purchase_offers 插件来管理应用内购买优惠。

import 'package:flutter/material.dart';
import 'package:in_app_purchase_offers/in_app_purchase_offers.dart';
import 'package:in_app_purchase_offers_example/store/store.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  final store = Store();

  MyApp({
    super.key,
  });

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: MyHomePage(
        title: 'Flutter Demo Home Page',
        store: store,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final Store store;

  const MyHomePage({
    super.key,
    required this.title,
    required this.store,
  });

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView(
          children: <Widget>[
            StreamBuilder(stream: widget.store.products,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return const Text('Loading...');
                }
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                }
                if (snapshot.data?.isEmpty == true) {
                  return const Text('No products found');
                }
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    for (var product in snapshot.requireData)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Product: ${product.title}'),
                          const SizedBox(height: 18),
                          Builder(
                            builder: (context) {
                              debugPrint(product.introductoryOffer?.forDisplay(context));
                              return Text('Intro Offer: ${product.introductoryOffer?.forDisplay(context)}', maxLines: 3);
                            }
                          ),
                          const SizedBox(height: 12),
                          for (final offer in product.promotionalOffers) ...[
                            Text(offer.id?.toString() ?? 'No ID', style: DefaultTextStyle.of(context).style.copyWith(fontWeight: FontWeight.bold)),
                            Builder(
                              builder: (context) {
                                debugPrint(offer.forDisplay(context));
                                return Text('Promo Offer: ${offer.forDisplay(context)}', maxLines: 3);
                              }
                            ),
                            const SizedBox(height: 12),
                          ],
                          const SizedBox(height: 24),
                        ],
                      )
                  ],
                );
              },
            ),
            const SizedBox(height: 24),
            TextButton(
              onPressed: () async {
                try {
                  await widget.store.queryProducts();
                } catch (e) {
                  debugPrint('Error: $e');
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Error: $e'))
                    );
                  }
                }
              },
              child: const Text('Query Products')
            ),
            const SizedBox(height: 12),
            TextButton(
              onPressed: () async {
                try {
                  await widget.store.restorePurchases();
                } catch (e) {
                  debugPrint('Error: $e');
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Error: $e'))
                    );
                  }
                }
              },
              child: const Text('Restore Purchases')
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 导入必要的库

    import 'package:flutter/material.dart';
    import 'package:in_app_purchase_offers/in_app_purchase_offers.dart';
    import 'package:in_app_purchase_offers_example/store/store.dart';
    
  2. 初始化应用

    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      final store = Store();
    
      MyApp({
        super.key,
      });
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: MyHomePage(
            title: 'Flutter Demo Home Page',
            store: store,
          ),
        );
      }
    }
    
  3. 创建主页面

    class MyHomePage extends StatefulWidget {
      final Store store;
    
      const MyHomePage({
        super.key,
        required this.title,
        required this.store,
      });
    
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
  4. 构建页面内容

    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text(widget.title),
          ),
          body: Center(
            child: ListView(
              children: <Widget>[
                StreamBuilder(stream: widget.store.products,
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return const Text('Loading...');
                    }
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    }
                    if (snapshot.data?.isEmpty == true) {
                      return const Text('No products found');
                    }
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        for (var product in snapshot.requireData)
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('Product: ${product.title}'),
                              const SizedBox(height: 18),
                              Builder(
                                builder: (context) {
                                  debugPrint(product.introductoryOffer?.forDisplay(context));
                                  return Text('Intro Offer: ${product.introductoryOffer?.forDisplay(context)}', maxLines: 3);
                                }
                              ),
                              const SizedBox(height: 12),
                              for (final offer in product.promotionalOffers) ...[
                                Text(offer.id?.toString() ?? 'No ID', style: DefaultTextStyle.of(context).style.copyWith(fontWeight: FontWeight.bold)),
                                Builder(
                                  builder: (context) {
                                    debugPrint(offer.forDisplay(context));
                                    return Text('Promo Offer: ${offer.forDisplay(context)}', maxLines: 3);
                                  }
                                ),
                                const SizedBox(height: 12),
                              ],
                              const SizedBox(height: 24),
                            ],
                          )
                      ],
                    );
                  },
                ),
                const SizedBox(height: 24),
                TextButton(
                  onPressed: () async {
                    try {
                      await widget.store.queryProducts();
                    } catch (e) {
                      debugPrint('Error: $e');
                      if (context.mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('Error: $e'))
                        );
                      }
                    }
                  },
                  child: const Text('Query Products')
                ),
                const SizedBox(height: 12),
                TextButton(
                  onPressed: () async {
                    try {
                      await widget.store.restorePurchases();
                    } catch (e) {
                      debugPrint('Error: $e');
                      if (context.mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('Error: $e'))
                        );
                      }
                    }
                  },
                  child: const Text('Restore Purchases')
                ),
              ],
            ),
          ),
        );
      }
    }
    

更多关于Flutter应用内购买优惠管理插件in_app_purchase_offers的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用内购买优惠管理插件in_app_purchase_offers的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


in_app_purchase_offers 是一个用于管理 Flutter 应用内购买优惠的插件。它允许开发者在应用内购买时设置和管理优惠,例如折扣、免费试用期等。以下是如何使用 in_app_purchase_offers 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 in_app_purchase_offers 依赖:

dependencies:
  flutter:
    sdk: flutter
  in_app_purchase_offers: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 初始化插件

在你的 Dart 文件中导入插件并进行初始化:

import 'package:in_app_purchase_offers/in_app_purchase_offers.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await InAppPurchaseOffers.initialize();
  runApp(MyApp());
}

3. 设置优惠

你可以通过 InAppPurchaseOffers 类来设置和管理应用内购买的优惠。例如,设置一个折扣优惠:

void setDiscountOffer() async {
  const String productId = 'com.example.product1';
  const double discountPrice = 0.99;  // 折扣价格
  const DateTime startDate = DateTime(2023, 10, 1);  // 优惠开始日期
  const DateTime endDate = DateTime(2023, 10, 31);  // 优惠结束日期

  try {
    await InAppPurchaseOffers.setDiscountOffer(
      productId: productId,
      discountPrice: discountPrice,
      startDate: startDate,
      endDate: endDate,
    );
    print('Discount offer set successfully');
  } catch (e) {
    print('Error setting discount offer: $e');
  }
}

4. 获取优惠信息

你可以通过 InAppPurchaseOffers 类来获取应用内购买的优惠信息:

void getDiscountOffer() async {
  const String productId = 'com.example.product1';

  try {
    final offer = await InAppPurchaseOffers.getDiscountOffer(productId: productId);
    if (offer != null) {
      print('Discount price: ${offer.discountPrice}');
      print('Start date: ${offer.startDate}');
      print('End date: ${offer.endDate}');
    } else {
      print('No discount offer found for product $productId');
    }
  } catch (e) {
    print('Error getting discount offer: $e');
  }
}

5. 移除优惠

你可以通过 InAppPurchaseOffers 类来移除应用内购买的优惠:

void removeDiscountOffer() async {
  const String productId = 'com.example.product1';

  try {
    await InAppPurchaseOffers.removeDiscountOffer(productId: productId);
    print('Discount offer removed successfully');
  } catch (e) {
    print('Error removing discount offer: $e');
  }
}

6. 监听优惠变化

你可以监听应用内购买优惠的变化,以便及时更新 UI:

void listenToOfferChanges() {
  InAppPurchaseOffers.offerChanges.listen((offer) {
    print('Offer changed: ${offer.productId}, ${offer.discountPrice}');
  });
}

7. 处理应用内购买

在处理应用内购买时,确保应用内购买逻辑与优惠逻辑结合使用。例如,在用户购买时应用优惠价格:

void purchaseProduct() async {
  const String productId = 'com.example.product1';

  try {
    final offer = await InAppPurchaseOffers.getDiscountOffer(productId: productId);
    final price = offer?.discountPrice ?? 1.99;  // 使用优惠价格或默认价格

    // 处理应用内购买逻辑
    // ...

  } catch (e) {
    print('Error purchasing product: $e');
  }
}
回到顶部