Flutter奖励系统插件tata_rewards的使用

Flutter奖励系统插件tata_rewards的使用

Tata Rewards 插件让你能够为你的 Flutter 应用添加支持奖励的功能。

安装

  1. pubspec.yaml 文件中添加最新版本的插件(然后运行 flutter pub get):
dependencies:
  tata_rewards: ^0.0.36
  1. 导入插件并在你的 Flutter 应用中使用它:
import 'package:tata_rewards/tata_rewards.dart';

示例

你可以修改以下属性:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:tata_rewards/tata_rewards.dart';

import 'firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  http.Client httpClient = http.Client();

  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  // 初始化SDK
  await MyRewardsSdk.instance.initialize(
    httpClient: httpClient,
    // tdlBaseUrl: "",
    tdlBaseUrl: "",
    tplBaseUrl: "",
  );

  await MyRewardsSdk.instance.notifyLogin(
      tdlToken:
      "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAyMWI0OTA4LWViMGQtNGVkNS05YjdmLWJiMjQ3MTBhNTg2ZiIsImV4dGVybmFsQ3VzdG9tZXJJZCI6IkZyZXNoQ3VzdG9tZXIwMDMiLCJvcmdfaWQiOiI3ZTEwNjE4Ny1jMmMxLTQ5YTMtODcyOC02ZDM3MzY2OTRiYWQiLCJvcmdhbmlzYXRpb25Db2RlIjoiVERMIiwiaWF0IjoxNzM4MDczMzcxLCJleHAiOjE3MzgyNDYxNzEsImlzcyI6IldhbGtpbiJ9.axcdXh5Pk2ziIppIG_MM8EGGyFTdrtz_y1B5mR-3GNF9WBkTIGg5KUnbL0Q5iNp4X8WTIK4u7hg_lxw7fF5HqLdP2zNruZWjm8aP_SyEwQptzWzo_g3dXgib7cRZ2zarBZhFSEHB1XqMNfugvXk2QBisVWGU-HNnoErsKmjiBDom0E88hZJO_UkUI--DL4WyNTu18z8RRLB7-hs5-fo8JsQcX1DoWDYqHMA5JTn6unX9gCnnS_K-lpARkirG1442dQDuEoshOt-6zq77W1WvtejxIswiK1iJvQyRNGh_1OchV5kL0_oVO15zrjXdjoVjXKdbNfb0DdG9bLWSoUadjA",
      tplToken: "");
  runApp(const MyApp());
}

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

  // 这个小部件是你的应用的根组件。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Gamification SDK',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

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

  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("My Rewards Sdk"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Center(
            child: ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => MyRewardsPage(
                        title: "My Rewards",
                        externalCustomerId: "Abhishek-14",
                        myRewardsPadding: 16,
                        onAwardClick: (rewardsTotal,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "the exact value $rewardsTotal ,$ctaLabel , $destinationUrl , $widgetIndex ,$pageArrayIndex");
                        },
                        onHistoryTabTaped: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "Taping on history tabs $ctaLabel,$destinationUrl,$widgetIndex,$pageArrayIndex");
                        },
                        onHistoryCardClick: (code,
                            rewardValue,
                            status,
                            ctaLabel,
                            destinationUrl,
                            brandName,
                            offerName) {
                          print(
                              "On Clicking of history card $code , $rewardValue , $status , $ctaLabel ,  $destinationUrl ,  $brandName , $offerName");
                        },
                        onProceedToQuizOrCollectNowCTAClick: (gameId,
                            status,
                            ctaLabel,
                            destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {},
                        onGoBackClicked: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "Navigating back to MyRewards $ctaLabel,$destinationUrl, $widgetIndex, $pageArrayIndex");
                        },
                        onMyRewardsPageEntrance: () {
                          print("We entered in to my rewards page");
                        },
                        onNavigateBack: (currentRoute, destinationRoute,
                            ctaLabel, pageIndex) {
                          print(
                              "navigating back from $currentRoute to $destinationRoute , $ctaLabel");
                        },
                        onRewardsDetailsEntrance: (ctaButton,
                            destinationUrl, widgetIndex, pageIndex) {
                          print(
                              "navigating to reward details page $ctaButton , $destinationUrl ,  $widgetIndex ,  $pageIndex");
                        },
                        onStartInvestingClick: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "on clicking of start investing $ctaLabel , $destinationUrl ,  $widgetIndex ,  $pageArrayIndex");
                        },
                        onRedeemNowCtaClicked: (code,
                            rewardValue,
                            status,
                            ctaLabel,
                            destinationUrl,
                            brandName,
                            offerName) {
                          print(
                              "on redeem now clicked $code , $rewardValue , $status ,  $destinationUrl ,  $ctaLabel , $brandName ,$offerName");
                        },
                        onDigitalGoldTotalScratchCardClicked: (total) {
                          print(
                              "on click of banner card on digital history section $total");
                        },
                        onNeuTotalScratchCardClicked: (total) {
                          print(
                              "on click of banner card on digital history section $total");
                        },
                        onExpiryScratchCardClick: (totalExpiredCount,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on click of expired card $totalExpiredCount , $destinationUrl , $widgetIndex , $pageArrayIndex");
                        },
                        onCopyCodeClicked: (code,
                            currentPageName,
                            rewardValue,
                            status,
                            ctaLabel,
                            expiresIn,
                            brandName,
                            offerName) {
                          print("on clicking copy code $code , $currentPageName , $rewardValue , $status ,  $expiresIn ,  $ctaLabel , $brandName ,$offerName");
                        },
                        onGetCodeCTAClicked: (code,
                            rewardValue,
                            status,
                            ctaLabel,
                            currentPage,
                            brandName,
                            expiresIn) {
                          print("on clicking get code $code , $rewardValue , $status ,  $currentPage ,  $ctaLabel , $brandName ,$expiresIn");
                        },
                        onStartShoppingClick: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "on clicking of start shopping $ctaLabel , $destinationUrl ,  $widgetIndex ,  $pageArrayIndex");
                        },
                        onHistoryPageEntrance: () {
                          print("We entered into history page");
                        },
                        onSubmitAnswerClicked: (question,
                            answerSelected,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on submitting answer $answerSelected,$question,$ctaLabel,$destinationUrl,$widgetIndex,$pageArrayIndex");
                        },
                        onSelectingOption: (question,
                            answerSelected,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on selecting different menu $answerSelected,$question,$ctaLabel,$destinationUrl,$widgetIndex,$pageArrayIndex");
                        },
                        onToSpinClick: (gameId,
                            status,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on to Spin Click $gameId,$status,$ctaLabel,$destinationUrl,$widgetIndex,$pageArrayIndex");
                        },
                        onSpinWheelCardClicked: (id, status, currentPage, ctaLabel,
                            destinationUrl, widgetIndex, pageIndex) {
                          print(
                              "On Spin The Wheel Taped $id,$status,$ctaLabel,$destinationUrl,$widgetIndex,$pageIndex");
                        },
                        onError: (errorCode, errorMessage, apiUrl) {
                          print(
                              "This is the current api error $errorCode ,  $errorMessage ,  $apiUrl ");
                        },
                        onScratchDialogOpen: (cardId, cardPoint, cardStatus,
                            currentRoute, brandName, businessCategory) {
                          print(
                              "We opened scratch card $cardId, $cardPoint ,$currentRoute ,$cardStatus  $brandName $businessCategory");
                        },
                        onCardScratched: (cardId,
                            cardReward,
                            cardStatus,
                            groupLevel,
                            destination,
                            widgetIndex,
                            pageIndex,
                            brandName,
                            businessCategory) {
                          print(
                              "When Card is scratched $cardId, $cardReward ,$cardStatus ,$groupLevel , $destination , $widgetIndex ,$pageIndex  $brandName $businessCategory");
                        },
                        onOfferDetailsPage: () {
                          print("we are navigation to offer details page");
                        },
                        onMyAllScratchCardEntrance: (availableScratchCard,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "navigating my all scratch card page $availableScratchCard $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onSpinnerPageEntrance: (gameId,
                            String? status,
                            String? ctaLabel,
                            String? destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {
                          print(
                              "we entered spin the wheel bottom sheet $status $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onReadInstructionClicked: (currentPage, action,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "on click on read instruction $currentPage $action $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onTermsAndConditionClicked: (currentPage,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "on click on terms &amp; condition $currentPage $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onSpinCtaClicked: (gameId, status, ctaLabel,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "on spin cta clicked $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },
                        onQuizPageEntrance: (gameId,
                            String? status,
                            String? ctaLabel,
                            String? destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {
                          print(
                              "we entered in quiz page entrance $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },
                        onProceedToQuizPageEntrance: (gameId,
                            String? status,
                            String? ctaLabel,
                            String? destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {
                          print(
                              "we entered in proceed to quiz page entrance $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },
                        onCongratulationsPageEntrance: (gameId,
                            String? status,
                            String? ctaLabel,
                            String? destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {
                          print(
                              "we entered in quiz page entrance $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },
                        onCollectNowCtaClicked: (gameId,
                            String? status,
                            String? ctaLabel,
                            String? destinationUrl,
                            String? widgetIndex,
                            String? pageArrayIndex) {
                          print(
                              "we entered in quiz page entrance $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },

                        onExpiryVoucherCardClick: (totalExpiryCount,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on click expiry voucher card $totalExpiryCount $ctaLabel ,  $destinationUrl , $widgetIndex , $pageArrayIndex");
                        },

                        onExpiryVoucherPageEntrance: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "Entered to expired promotion page $ctaLabel ,  $destinationUrl , $widgetIndex , $pageArrayIndex");
                        },

                        onExpiryScratchPageEntrance: (ctaLabel, destinationUrl,
                            widgetIndex, pageArrayIndex) {
                          print(
                              "Entered to expired scratch page $ctaLabel ,  $destinationUrl , $widgetIndex , $pageArrayIndex");
                        },
                        onProceedToQuizCTAClicked: (gameId,
                            status,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "on click on proceed to quiz cta $gameId ,  $status , $ctaLabel , $destinationUrl , $widgetIndex $pageArrayIndex");
                        },
                        onMyAllSpinCardEntrance: (availableSpinCards,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "we entered my all spin the wheel cards $availableSpinCards $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onDealOfTheDayProductClick: (bannerId, ctaLabel,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "when we are clicking on filter of products $bannerId $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onViewAllScratchCardCTAClick: (availableScratchCard,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex) {
                          print(
                              "checking the value view all cards $availableScratchCard $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onDealOfTheDayBannerClick: (bannerId, ctaLabel,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "when we are clicking on banner of products $bannerId $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onReferAndEarnClick: (bannerId, ctaLabel,
                            destinationUrl, widgetIndex, pageArrayIndex) {
                          print(
                              "when we are clicking on Refer and Earn $bannerId $ctaLabel $destinationUrl $widgetIndex $pageArrayIndex");
                        },
                        onScratchCardClick: (id,
                            point,
                            status,
                            currentPage,
                            ctaLabel,
                            destinationUrl,
                            widgetIndex,
                            pageArrayIndex,
                            brandName,
                            businessCategory) {
                          print(
                              "When we are clicking on scratch card on rewards page $id , $point, $status, $ctaLabel, $currentPage , $destinationUrl, $widgetIndex , $pageArrayIndex $brandName $businessCategory");
                        },
                        sectionGap: const SizedBox(
                          height: 24,
                        ),
                      )),
                );
              },
              child: const Text("Gamification Sdk"),
            ),
          )
        ],
      ),
    );
  }
}

更多关于Flutter奖励系统插件tata_rewards的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter奖励系统插件tata_rewards的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


tata_rewards 是一个用于 Flutter 的奖励系统插件,通常用于在应用中实现用户积分、奖励、任务完成等功能。以下是如何在 Flutter 项目中使用 tata_rewards 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 tata_rewards 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  tata_rewards: ^latest_version

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

2. 初始化插件

在你的 Flutter 应用启动时,通常需要在 main.dart 文件中初始化 tata_rewards 插件。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 tata_rewards
  await TataRewards.initialize(
    apiKey: 'YOUR_API_KEY',
    userId: 'USER_ID',
  );

  runApp(MyApp());
}

3. 获取用户积分

你可以使用 TataRewards 提供的 API 来获取用户的积分。

int userPoints = await TataRewards.getUserPoints();
print('User Points: $userPoints');

4. 增加用户积分

当用户完成某个任务或行为时,你可以增加用户的积分。

await TataRewards.addPoints(points: 10, reason: 'Completed Task');

5. 减少用户积分

你也可以减少用户的积分,例如当用户兑换奖励时。

await TataRewards.deductPoints(points: 5, reason: 'Redeemed Reward');

6. 监听积分变化

你可以监听用户积分的变化,以便在 UI 上实时更新。

TataRewards.onPointsChanged.listen((int newPoints) {
  print('Points changed: $newPoints');
  // 更新 UI
});

7. 获取用户奖励历史

你可以获取用户的奖励历史记录。

List<RewardHistory> history = await TataRewards.getRewardHistory();
history.forEach((reward) {
  print('Reward: ${reward.rewardName}, Points: ${reward.points}, Date: ${reward.date}');
});

8. 兑换奖励

当用户想要兑换某个奖励时,可以使用以下方法。

await TataRewards.redeemReward(rewardId: 'REWARD_ID');

9. 处理错误

在使用插件时,可能会遇到错误,建议对错误进行处理。

try {
  await TataRewards.addPoints(points: 10, reason: 'Completed Task');
} catch (e) {
  print('Error adding points: $e');
}

10. 示例 UI

以下是一个简单的 UI 示例,展示如何显示用户积分并允许用户增加积分。

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

class RewardScreen extends StatefulWidget {
  [@override](/user/override)
  _RewardScreenState createState() => _RewardScreenState();
}

class _RewardScreenState extends State<RewardScreen> {
  int _userPoints = 0;

  [@override](/user/override)
  void initState() {
    super.initState();
    _loadUserPoints();
  }

  Future<void> _loadUserPoints() async {
    int points = await TataRewards.getUserPoints();
    setState(() {
      _userPoints = points;
    });
  }

  Future<void> _addPoints() async {
    try {
      await TataRewards.addPoints(points: 10, reason: 'Completed Task');
      _loadUserPoints();
    } catch (e) {
      print('Error adding points: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Reward System'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Your Points: $_userPoints',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _addPoints,
              child: Text('Add 10 Points'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部