Flutter壁纸管理插件superwallkit_flutter的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter壁纸管理插件superwallkit_flutter的使用

简介

Superwall 是一个开源框架,提供了一个用于呈现和创建付费墙(paywalls)的封装。它与 Superwall 后端交互,让您能够轻松地在应用中动态迭代付费墙。

特性

  • ✅ 服务器端付费墙迭代
  • 🎯 转化率跟踪 - 了解用户是否在看到付费墙后进行了转化
  • 🆓 试用开始率跟踪 - 测量您的试用开始率
  • 📊 分析 - 自动计算指标如转化率和展示次数
  • ✏️ A/B 测试 - 自动计算不同付费墙的指标
  • 📝 在线文档 - 最新文档
  • 🔀 集成 - 超过一打集成,方便发送转化数据到您需要的地方
  • 💯 维护良好 - 频繁发布
  • 📮 支持优秀 - 发邮件给创始人: jake@superwall.com

安装

首先,您需要在项目中添加 superwallkit_flutter 插件。在 pubspec.yaml 文件中添加以下依赖:

dependencies:
  superwallkit_flutter: ^latest_version

然后运行 flutter pub get 来安装插件。

开始使用

  1. 注册免费账户 并阅读我们的文档
  2. 按照下面的示例代码进行集成。

示例代码

以下是完整的示例代码,展示了如何使用 superwallkit_flutter 插件来实现付费墙功能。

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:superwallkit_flutter/superwallkit_flutter.dart';
import 'RCPurchaseController.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> implements SuperwallDelegate {
  final logging = Logging();

  @override
  void initState() {
    const useRevenueCat = true;

    super.initState();
    configureSuperwall(useRevenueCat);
  }

  // Configure Superwall
  Future<void> configureSuperwall(bool useRevenueCat) async {
    try {
      // MARK: Step 1 - Create your Purchase Controller
      /// Create an `RCPurchaseController()` wherever Superwall and RevenueCat are being initialized.
      final purchaseController = RCPurchaseController();

      // Get Superwall API Key
      final apiKey = Platform.isIOS
          ? 'pk_5f6d9ae96b889bc2c36ca0f2368de2c4c3d5f6119aacd3d2'
          : 'pk_d1f0959f70c761b1d55bb774a03e22b2b6ed290ce6561f85';

      final logging = Logging();
      logging.level = LogLevel.warn;
      logging.scopes = {LogScope.all};

      final options = SuperwallOptions();
      options.paywalls.shouldPreload = false;
      // options.logging = logging;

      // MARK: Step 2 - Configure Superwall
      /// Always configure Superwall first. Pass in the `purchaseController` you just created.
      Superwall.configure(apiKey,
          purchaseController: useRevenueCat ? purchaseController : null,
          options: options, completion: () {
        logging.info('Executing Superwall configure completion block');
      });

      Superwall.shared.setDelegate(this);

      // MARK: Step 3 – Configure RevenueCat and Sync Subscription Status
      /// Always configure RevenueCat after Superwall and keep Superwall's
      /// subscription status up-to-date with RevenueCat's.
      if (useRevenueCat) {
        await purchaseController.configureAndSyncSubscriptionStatus();
      }
    } catch (e) {
      // Handle any errors that occur during configuration
      logging.error('Failed to configure Superwall:', e);
    }
  }

  // Method to call when the button is tapped
  Future<void> onRegisterTapped() async {
    try {
      final handler = PaywallPresentationHandler();
      handler
        ..onPresent((paywallInfo) async {
          final name = await paywallInfo.name;
          logging.info('Handler (onPresent): $name');
        })
        ..onDismiss((paywallInfo) async {
          final name = await paywallInfo.name;
          logging.info('Handler (onDismiss): $name');
        })
        ..onError((error) {
          logging.error('Handler (onError):', error);
        })
        ..onSkip(handleSkipReason);

      Superwall.shared.registerEvent('flutter', handler: handler, feature: () {
        logging.info('Executing feature block');
        performFeatureBlockActions();
      });
      logging.info('Register method called successfully.');
    } catch (e) {
      // Handle any errors that occur during registration
      logging.error('Failed to call register method:', e);
    }
  }

  Future<void> performFeatureBlockActions() async {
    final paywallInfo = await Superwall.shared.getLatestPaywallInfo();

    if (paywallInfo != null) {
      final identifier = await paywallInfo.identifier;
      logging.info('Identifier: $identifier');

      final experiment = await paywallInfo.experiment;
      logging.info('Experiment: $experiment');

      final triggerSessionId = await paywallInfo.triggerSessionId;
      logging.info('Trigger Session ID: $triggerSessionId');

      final products = await paywallInfo.products;
      logging.info('Products: $products');

      final productIds = await paywallInfo.productIds;
      logging.info('Product IDs: $productIds');

      final name = await paywallInfo.name;
      logging.info('Name: $name');

      final url = await paywallInfo.url;
      logging.info('URL: $url');

      final presentedByEventWithName =
          await paywallInfo.presentedByEventWithName;
      logging.info('Presented By Event With Name: $presentedByEventWithName');

      final presentedByEventWithId = await paywallInfo.presentedByEventWithId;
      logging.info('Presented By Event With Id: $presentedByEventWithId');

      final presentedByEventAt = await paywallInfo.presentedByEventAt;
      logging.info('Presented By Event At: $presentedByEventAt');

      final presentedBy = await paywallInfo.presentedBy;
      logging.info('Presented By: $presentedBy');

      final presentationSourceType = await paywallInfo.presentationSourceType;
      logging.info('Presentation Source Type: $presentationSourceType');

      final responseLoadStartTime = await paywallInfo.responseLoadStartTime;
      logging.info('Response Load Start Time: $responseLoadStartTime');

      final responseLoadCompleteTime =
          await paywallInfo.responseLoadCompleteTime;
      logging.info('Response Load Complete Time: $responseLoadCompleteTime');

      final responseLoadFailTime = await paywallInfo.responseLoadFailTime;
      logging.info('Response Load Fail Time: $responseLoadFailTime');

      final responseLoadDuration = await paywallInfo.responseLoadDuration;
      logging.info('Response Load Duration: $responseLoadDuration');

      final webViewLoadStartTime = await paywallInfo.webViewLoadStartTime;
      logging.info('Web View Load Start Time: $webViewLoadStartTime');

      final webViewLoadCompleteTime = await paywallInfo.webViewLoadCompleteTime;
      logging.info('Web View Load Complete Time: $webViewLoadCompleteTime');

      final webViewLoadFailTime = await paywallInfo.webViewLoadFailTime;
      logging.info('Web View Load Fail Time: $webViewLoadFailTime');

      final webViewLoadDuration = await paywallInfo.webViewLoadDuration;
      logging.info('Web View Load Duration: $webViewLoadDuration');

      final productsLoadStartTime = await paywallInfo.productsLoadStartTime;
      logging.info('Products Load Start Time: $productsLoadStartTime');

      final productsLoadCompleteTime =
          await paywallInfo.productsLoadCompleteTime;
      logging.info('Products Load Complete Time: $productsLoadCompleteTime');

      final productsLoadFailTime = await paywallInfo.productsLoadFailTime;
      logging.info('Products Load Fail Time: $productsLoadFailTime');

      final productsLoadDuration = await paywallInfo.productsLoadDuration;
      logging.info('Products Load Duration: $productsLoadDuration');

      final paywalljsVersion = await paywallInfo.paywalljsVersion;
      logging.info('Paywall.js Version: $paywalljsVersion');

      final isFreeTrialAvailable = await paywallInfo.isFreeTrialAvailable;
      logging.info('Is Free Trial Available: $isFreeTrialAvailable');

      final featureGatingBehavior = await paywallInfo.featureGatingBehavior;
      logging.info('Feature Gating Behavior: $featureGatingBehavior');

      final closeReason = await paywallInfo.closeReason;
      logging.info('Close Reason: $closeReason');

      final localNotifications = await paywallInfo.localNotifications;
      logging.info('Local Notifications: $localNotifications');

      final computedPropertyRequests =
          await paywallInfo.computedPropertyRequests;
      logging.info('Computed Property Requests: $computedPropertyRequests');

      final surveys = await paywallInfo.surveys;
      logging.info('Surveys: $surveys');
    } else {
      logging.info('Paywall Info is null');
    }
  }

  Future<void> performAction() async {
    try {
      await Superwall.shared.identify('123456');

      final userId = await Superwall.shared.getUserId();
      logging.info(userId);

      await Superwall.shared.setUserAttributes({'someAttribute': 'someValue'});
      final attributes1 = await Superwall.shared.getUserAttributes();
      logging.info('$attributes1}');

      await Superwall.shared
          .setUserAttributes({'jack': 'lost', 'kate': 'antman'});
      final attributes2 = await Superwall.shared.getUserAttributes();
      logging.info('$attributes2}');

      await Superwall.shared.setUserAttributes({
        'jack': '123',
        'kate': {'tv': 'series'}
      });
      final attributes3 = await Superwall.shared.getUserAttributes();
      logging.info('$attributes3');

      await Superwall.shared.reset();

      final attributes4 = await Superwall.shared.getUserAttributes();
      logging.info('$attributes4');

      Superwall.shared.setLogLevel(LogLevel.error);
      final logLevel = await Superwall.shared.getLogLevel();
      logging.info('Log Level: $logLevel');
    } catch (e) {
      logging.error('Failed perform action:', e);
    }
  }

  Future<void> handleSkipReason(PaywallSkippedReason skipReason) async {
    final description = await skipReason.description;

    if (skipReason is PaywallSkippedReasonHoldout) {
      final experiment = await skipReason.experiment;
      final experimentId = await experiment.id;
      logging.info('Holdout with experiment: $experimentId');
      logging.info('Handler (onSkip): $description');
    } else if (skipReason is PaywallSkippedReasonNoRuleMatch) {
      logging.info('Handler (onSkip): $description');
    } else if (skipReason is PaywallSkippedReasonEventNotFound) {
      logging.info('Handler (onSkip): $description');
    } else if (skipReason is PaywallSkippedReasonUserIsSubscribed) {
      logging.info('Handler (onSkip): $description');
    } else {
      logging.info('Handler (onSkip): Unknown skip reason');
    }
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            title: const Text('Flutter superapp'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text('Running'),
                ElevatedButton(
                  onPressed: onRegisterTapped,
                  child: const Text('Register event'),
                ),
                ElevatedButton(
                  onPressed: performAction,
                  child: const Text('Perform action'),
                ),
              ],
            ),
          ),
        ),
      );

  @override
  void didDismissPaywall(PaywallInfo paywallInfo) {
    logging.info('didDismissPaywall: $paywallInfo');
  }

  @override
  void didPresentPaywall(PaywallInfo paywallInfo) {
    logging.info('didPresentPaywall: $paywallInfo');
  }

  @override
  void handleCustomPaywallAction(String name) {
    logging.info('handleCustomPaywallAction: $name');
  }

  @override
  void handleLog(String level, String scope, String? message,
      Map<dynamic, dynamic>? info, String? error) {
    // logging.info("handleLog: $level, $scope, $message, $info, $error");
  }

  @override
  Future<void> handleSuperwallEvent(SuperwallEventInfo eventInfo) async {
    // This delegate function is noisy. Uncomment to debug.
    //logging.info('handleSuperwallEvent: $eventInfo');
    //switch (eventInfo.event.type) {
    //  case EventType.appOpen:
    //    logging.info('appOpen event');
    //  case EventType.deviceAttributes:
    //    logging.info('deviceAttributes event: ${eventInfo.event.deviceAttributes} ');
    //  case EventType.paywallOpen:
    //    final paywallInfo = eventInfo.event.paywallInfo;
    //    logging.info('paywallOpen event: $paywallInfo ');
    //
    //    if (paywallInfo != null) {
    //      final identifier = await paywallInfo.identifier;
    //      logging.info('paywallInfo.identifier: $identifier ');
    //
    //      final productIds = await paywallInfo.productIds;
    //      logging.info('paywallInfo.productIds: $productIds ');
    //    }
    //  default:
    //    break;
    //}
  }

  @override
  void paywallWillOpenDeepLink(Uri url) {
    logging.info('paywallWillOpenDeepLink: $url');
  }

  @override
  void paywallWillOpenURL(Uri url) {
    logging.info('paywallWillOpenURL: $url');
  }

  @override
  void subscriptionStatusDidChange(SubscriptionStatus newValue) {
    logging.info('subscriptionStatusDidChange: $newValue');
  }

  @override
  void willDismissPaywall(PaywallInfo paywallInfo) {
    logging.info('willDismissPaywall: $paywallInfo');
  }

  @override
  void willPresentPaywall(PaywallInfo paywallInfo) {
    printSubscriptionStatus();
    logging.info('willPresentPaywall: $paywallInfo');
  }

  Future<void> printSubscriptionStatus() async {
    final status = await Superwall.shared.getSubscriptionStatus();
    final description = await status.description;

    logging.info('Status: $description');
  }
}

总结

通过上述步骤和示例代码,您可以轻松地在 Flutter 应用中集成 Superwall 的付费墙功能。请确保参考官方文档以获取更多详细信息和高级配置选项。


更多关于Flutter壁纸管理插件superwallkit_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter壁纸管理插件superwallkit_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 superwallkit_flutter 插件来管理壁纸的示例代码。这个插件假设提供了加载、设置和管理壁纸的功能。不过,请注意,具体的API和实现细节可能因插件版本和更新而有所变化,请参考官方文档以确保准确性。

首先,你需要在你的 pubspec.yaml 文件中添加 superwallkit_flutter 依赖:

dependencies:
  flutter:
    sdk: flutter
  superwallkit_flutter: ^latest_version  # 请替换为最新的版本号

然后运行 flutter pub get 来获取依赖。

接下来,在你的 Flutter 应用中使用这个插件。以下是一个简单的示例,展示如何加载和设置壁纸。

import 'package:flutter/material.dart';
import 'package:superwallkit_flutter/superwallkit_flutter.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  SuperWallKitController? _wallKitController;

  @override
  void initState() {
    super.initState();
    // 初始化 SuperWallKitController
    _wallKitController = SuperWallKitController();
    // 加载壁纸列表(假设有一个API可以获取壁纸列表)
    _loadWallpapers();
  }

  @override
  void dispose() {
    _wallKitController?.dispose();
    super.dispose();
  }

  Future<void> _loadWallpapers() async {
    // 假设这里有一个API调用获取壁纸列表
    // 例如:List<Wallpaper> wallpapers = await _wallKitController!.fetchWallpapers();
    // 这里我们直接使用一些示例数据
    List<String> exampleWallpapers = [
      'https://example.com/wallpaper1.jpg',
      'https://example.com/wallpaper2.jpg',
      // 更多壁纸URL...
    ];

    // 设置壁纸列表(这里假设插件有一个设置壁纸列表的方法)
    // 注意:这里的API调用是假设的,实际使用时请参考插件文档
    for (String url in exampleWallpapers) {
      await _wallKitController!.addWallpaper(url);
    }
  }

  Future<void> _setWallpaper(String wallpaperUrl) async {
    // 设置指定的壁纸
    // 注意:这里的API调用是假设的,实际使用时请参考插件文档
    await _wallKitController!.setCurrentWallpaper(wallpaperUrl);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('SuperWallKit Flutter Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  // 这里我们假设第一个壁纸URL是要设置的壁纸
                  List<String> exampleWallpapers = [
                    'https://example.com/wallpaper1.jpg',
                    // 更多壁纸URL...
                  ];
                  if (exampleWallpapers.isNotEmpty) {
                    await _setWallpaper(exampleWallpapers.first);
                  }
                },
                child: Text('Set First Wallpaper'),
              ),
              // 可以添加更多按钮或逻辑来管理壁纸
            ],
          ),
        ),
      ),
    );
  }
}

注意

  1. 上述代码中的 _wallKitController!.fetchWallpapers()_wallKitController!.addWallpaper(url)_wallKitController!.setCurrentWallpaper(wallpaperUrl) 是假设的方法调用。实际使用时,请参考 superwallkit_flutter 插件的官方文档来了解正确的API调用方式。
  2. 示例中的壁纸URL是虚构的,你需要替换为实际的壁纸URL或从你的后端API获取壁纸数据。
  3. 错误处理和状态管理(如加载状态、错误消息等)在实际应用中也是非常重要的,这里为了简洁而省略了。

确保你已经仔细阅读并理解了 superwallkit_flutter 插件的官方文档,以便正确实现所需功能。

回到顶部