Flutter应用增益插件appgain_sdk的使用

Flutter应用增益插件appgain_sdk的使用

本教程旨在指导用户如何将跨平台的Flutter应用与Appgain.io云服务集成,并使用Appgain.io的产品。要将Appgain SDK集成到您的Flutter应用中,您需要使用Appgain.io的pub dev库。

对于已经集成了Appgain SDK的iOS和Android Flutter应用程序,请参阅我们的Appgain Flutter TestApp

配置指南

详细的配置步骤可以查看Appgain SDK配置指南


完整示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用appgain_sdk插件。

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:appgain_sdk/appgain_sdk.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // 这个小部件是你的应用的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Appgain SDK',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(title: 'Flutter Appgain SDK'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
    Timer.run(initUser);
  }

  initUser() {
    initSDKDialog();
  }

  initUserWithResultDialog() {
    Appgain()
        .initAppgainSDK(appId: appId, appKey: apiKey)
        .then((result) => showAlertDialog(result.toString()));
  }

  getUserId() {
    Appgain()
        .getUserId()
        .then((result) => showAlertDialog('UserId = ${result.toString()}'));
  }

  matchLink() {
    Appgain().matchLink().then((result) {
      showAlertDialog('MatchLink Response = ${result.toString()}');
      if (result != null) {
        (result['extra_data']);
        (result['extra_data']['params']);
        (result['extra_data']['userId']);
        (result['smart_link_primary']);
        (result['smart_link_url']);
        (result['smart_link_id']);
      }
    });
  }

  String? appId;
  String? apiKey;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
          child: Center(
        child: Column(children: [
          const SizedBox(height: 10),
          InvokeButton(
              buttonName: '初始化',
              function: () => initUserWithResultDialog()),
          InvokeButton(
              buttonName: '通过子域名初始化',
              function: () => initSubdomainWithResultDialog()),
          InvokeButton(buttonName: '获取用户ID', function: () => getUserId()),
          InvokeButton(buttonName: '匹配链接', function: () => matchLink()),
          InvokeButton(
              buttonName: '触发自动器',
              function: () => fireAutomatorDialog()),
          InvokeButton(
              buttonName: '触发自动器(个性化)',
              function: () => fireAutomatorWithPersonalizationDialog()),
          InvokeButton(
              buttonName: '取消触发自动器',
              function: () => cancelFireAutomatorDialog()),
          InvokeButton(
              buttonName: '添加购买记录',
              function: () => logPurchaseDialog()),
          InvokeButton(
              buttonName: "更新用户ID",
              function: () => updateUserIdDialog()),
          InvokeButton(
              buttonName: '更新用户数据',
              function: () => updateUserDialog()),
          InvokeButton(
              buttonName: '添加电子邮件通知渠道',
              function: () => emailNotificationChannelDialog()),
          InvokeButton(
              buttonName: '添加短信通知渠道',
              function: () => smsNotificationChannelDialog()),
          InvokeButton(
              buttonName: '记录事件',
              function: () => logEventDialog()),
        ]),
      )), // 这个尾部逗号使构建方法更美观。
    );
  }

  final _subdomainController = TextEditingController();
  final _appIdController = TextEditingController();
  final _apiKeyController = TextEditingController();
  final _triggerPointController = TextEditingController();
  final _automatorKeyController = TextEditingController();
  final _automatorValueController = TextEditingController();
  final _newUserIdController = TextEditingController();
  final _emailNotificationChannelController = TextEditingController();
  final _smsNotificationChannelController = TextEditingController();
  final _productNameController = TextEditingController();
  final _amountController = TextEditingController();
  final _currencyController = TextEditingController();
  final _userEmailController = TextEditingController();
  final _userPhoneController = TextEditingController();
  final _enableNotificationChannelController = TextEditingController();
  final _textFieldController2 = TextEditingController();
  final _textFieldController1 = TextEditingController();
  final _typeController = TextEditingController();
  final _actionController = TextEditingController();
  final _logEventKeyController = TextEditingController();
  final _logEventValueController = TextEditingController();

  initSDKDialog() async {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: const Text('初始化SDK'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 100,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _appIdController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration("APP ID"),
                  ),
                  TextField(
                    controller: _apiKeyController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration("API KEY"),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  if (kDebugMode) {
                    _appIdController.text = '62f10c04d2f863000fc14490';
                    _apiKeyController.text = '54398767a0bbc815d98c1065e9d2145d1b88d1d9f36f4646906b17d7ea154c85';
                  }
                  appId = _appIdController.text;
                  apiKey = _apiKeyController.text;
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        });
  }

  fireAutomatorDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('触发自动器'),
            content: //&lt;Widget&gt;[
                SizedBox(
                    height: 50,
                    child: TextField(
                      controller: _triggerPointController,
                      textInputAction: TextInputAction.go,
                      //  keyboardType: TextInputType.text(),
                      decoration: inputDecoration("触发点名称"),
                    )),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .fireAutomator(triggerPoint: _triggerPointController.text)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  fireAutomatorWithPersonalizationDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('触发自动器(个性化)'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 145,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _triggerPointController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration('触发点名称'),
                  ),
                  TextField(
                    controller: _automatorKeyController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration('键'),
                  ),
                  TextField(
                    controller: _automatorValueController,
                    textInputAction: TextInputAction.done,
                    decoration: inputDecoration('值'),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  var personalizationData = {
                    _automatorKeyController.text:
                        _automatorValueController.text,
                  };
                  await Appgain()
                      .fireAutomatorWithPersonalization(
                          triggerPoint: _triggerPointController.text,
                          personalizationMap: personalizationData)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  cancelFireAutomatorDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('取消触发自动器'),
            content: //&lt;Widget&gt;[
                SizedBox(
                    height: 50,
                    child: TextField(
                      controller: _triggerPointController,
                      textInputAction: TextInputAction.done,
                      //  keyboardType: TextInputType.text(),
                      decoration: inputDecoration("触发点名称"),
                    )),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .cancelFireAutomator(
                          triggerPoint: _triggerPointController.text)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  updateUserIdDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('更新用户ID'),
            content: //&lt;Widget&gt;[
                SizedBox(
                    height: 50,
                    child: TextField(
                      controller: _newUserIdController,
                      textInputAction: TextInputAction.done,
                      //  keyboardType: TextInputType.text(),
                      decoration: inputDecoration("新用户ID"),
                    )),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .setUserId(userId: _newUserIdController.text)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  emailNotificationChannelDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('创建通知渠道'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 50,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _emailNotificationChannelController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration('输入电子邮件'),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .addNotificationChannel(
                        notificationType: 'email',
                        item: _emailNotificationChannelController.value.text,
                      )
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  smsNotificationChannelDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('创建通知渠道'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 50,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _smsNotificationChannelController,
                    textInputAction: TextInputAction.done,
                    decoration: inputDecoration("输入手机号码"),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain().addNotificationChannel(
                      notificationType: 'SMS',
                      item: _smsNotificationChannelController.value.text);
                },
              )
            ],
          );
        });
  }

  logPurchaseDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('添加购买记录'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 150,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _productNameController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration('产品名称'),
                  ),
                  TextField(
                    controller: _amountController,
                    textInputAction: TextInputAction.go,
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    decoration: inputDecoration('金额'),
                  ),
                  TextField(
                    controller: _currencyController,
                    textInputAction: TextInputAction.done,
                    decoration: inputDecoration('货币'),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .addPurchase(
                          productName: _productNameController.text,
                          amount: _amountController.text == ''
                              ? 0
                              : double.parse(_amountController.text),
                          currency: _currencyController.text)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  updateUserDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('更新用户信息'),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 200,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _userEmailController,
                    textInputAction: TextInputAction.go,
                    //  keyboardType: TextInputType.text(),
                    decoration: inputDecoration('用户电子邮件'),
                  ),
                  TextField(
                    controller: _userPhoneController,
                    textInputAction: TextInputAction.next,
                    //  keyboardType: TextInputType.text(),
                    decoration: inputDecoration('电话号码'),
                  ),
                  TextField(
                    controller: _textFieldController1,
                    textInputAction: TextInputAction.next,
                    //  keyboardType: TextInputType.text(),
                    decoration: inputDecoration('字段一'),
                  ),
                  TextField(
                    controller: _textFieldController2,
                    textInputAction: TextInputAction.done,
                    //  keyboardType: TextInputType.text(),
                    decoration: inputDecoration('字段二'),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  var updatedData = {
                    'userEmail': _userEmailController.text,
                    'phone': _userPhoneController.text,
                    'updatedField1': _textFieldController1.text,
                    "updatedField2": _textFieldController2.text
                  };
                  await Appgain()
                      .updateUser(data: updatedData)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  enableNotificationChannelDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('启用通知渠道'.toUpperCase()),
            content: //&lt;Widget&gt;[
                SizedBox(
              height: 50,
              child: Column(
                children: &lt;Widget&gt;[
                  TextField(
                    controller: _enableNotificationChannelController,
                    textInputAction: TextInputAction.go,
                    decoration: inputDecoration("通知类型"),
                  ),
                ],
              ),
            ),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain()
                      .enableReceiveNotification(
                          type: _enableNotificationChannelController.text)
                      .then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  logEventDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('记录事件'),
            content: //&lt;Widget&gt;[
                SizedBox(
                    height: 200,
                    child: Column(
                      children: &lt;Widget&gt;[
                        TextField(
                          controller: _typeController,
                          textInputAction: TextInputAction.go,
                          decoration: inputDecoration('类型'),
                        ),
                        TextField(
                          controller: _actionController,
                          textInputAction: TextInputAction.go,
                          decoration: inputDecoration('操作'),
                        ),
                        TextField(
                          controller: _logEventKeyController,
                          textInputAction: TextInputAction.go,
                          decoration: inputDecoration('键'),
                        ),
                        TextField(
                          controller: _logEventValueController,
                          textInputAction: TextInputAction.done,
                          decoration: inputDecoration('值'),
                        ),
                      ],
                    )),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  await Appgain().logEvent(
                    type: _typeController.value.text,
                    action: _actionController.value.text,
                    extras: {
                      _logEventKeyController.value.text:
                          _logEventValueController.value.text
                    },
                  ).then((value) => showAlertDialog(value.toString()));
                },
              )
            ],
          );
        });
  }

  initSubdomainWithResultDialog() async {
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('记录事件'),
            content: //&lt;Widget&gt;[
                SizedBox(
                    height: 50,
                    child: Column(
                      children: &lt;Widget&gt;[
                        TextField(
                          controller: _subdomainController,
                          textInputAction: TextInputAction.go,
                          decoration: inputDecoration('子域名'),
                        ),
                      ],
                    )),
            actions: &lt;Widget&gt;[
              TextButton(
                child: const Text('确定'),
                onPressed: () async {
                  Navigator.of(context).pop();
                  Appgain()
                      .initAppgainSDKWithSubdomain(appId: appId, appKey: apiKey, subdomain: _subdomainController.value.text)
                      .then((result) => showAlertDialog(result.toString()));
                },
              )
            ],
          );
        });
  }

  showAlertDialog(String message) {
    return showDialog(
        context: context,
        useRootNavigator: false,
        builder: (_) => AlertDialog(
              title: const Text(''),
              content: Text(message),
              actions: [
                TextButton(
                  child: const Text("确定"),
                  onPressed: () {
                    Navigator.pop(_);
                  },
                )
              ],
            ));
  }

  InputDecoration inputDecoration(String? message) =>
      InputDecoration(hintText: message!);
}

class InvokeButton extends StatelessWidget {
  final String? buttonName;
  final Function function;

  const InvokeButton(
      {Key? key, required this.buttonName, required this.function})
      : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      width: double.infinity - 20,
      child: OutlinedButton(
        child: Text(buttonName!.toUpperCase()),
        onPressed: () {
          function();
        },
        style: OutlinedButton.styleFrom(
          primary: Colors.white,
          backgroundColor: Colors.teal,
        ),
      ),
    );
  }
}

更多关于Flutter应用增益插件appgain_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


appgain_sdk 是一个用于增强 Flutter 应用功能的插件。它通常用于实现用户行为分析、推送通知、A/B 测试、个性化推荐等功能。以下是如何在 Flutter 应用中使用 appgain_sdk 的基本步骤:

1. 添加依赖

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

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

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

2. 初始化 SDK

在你的 Flutter 应用的 main.dart 文件中,初始化 appgain_sdk。通常你需要在应用的入口点 (main 函数) 中执行此操作。

import 'package:appgain_sdk/appgain_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 Appgain SDK
  await Appgain.init(
    apiKey: 'YOUR_API_KEY', // 替换为你的 Appgain API 密钥
  );
  
  runApp(MyApp());
}

3. 配置用户标识

如果你的应用有用户登录功能,你需要在用户登录后设置用户标识,以便 appgain_sdk 可以跟踪用户行为。

Appgain.setUserIdentifier('USER_ID'); // 替换为实际的用户 ID

4. 跟踪事件

你可以使用 appgain_sdk 来跟踪用户的行为事件。例如,跟踪用户点击按钮的事件:

Appgain.logEvent('button_clicked', {'button_id': 'home_button'});

5. 实现 A/B 测试

appgain_sdk 支持 A/B 测试功能。你可以使用它来测试不同的应用版本或功能。

final variant = await Appgain.getABTestVariant('experiment_id');
if (variant == 'A') {
  // 执行 A 版本的逻辑
} else {
  // 执行 B 版本的逻辑
}

6. 推送通知

appgain_sdk 还支持推送通知功能。你可以在应用中配置推送通知:

Appgain.enablePushNotifications();

7. 个性化推荐

你可以使用 appgain_sdk 来获取个性化推荐内容:

final recommendations = await Appgain.getRecommendations('recommendation_id');
// 使用推荐内容更新 UI

8. 处理生命周期事件

在 Flutter 应用中,你可以监听应用的生命周期事件,并在适当的时机调用 appgain_sdk 的方法:

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      Appgain.appResumed();
    } else if (state == AppLifecycleState.paused) {
      Appgain.appPaused();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Appgain SDK Example'),
        ),
        body: Center(
          child: Text('Hello, Appgain!'),
        ),
      ),
    );
  }
}

9. 调试与日志

在开发过程中,你可以启用调试日志来查看 appgain_sdk 的输出:

Appgain.setDebugEnabled(true);
回到顶部