Flutter客户服务插件helpshift_wrapper的使用

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

Flutter客户服务插件helpshift_wrapper的使用

插件简介

helpshift_wrapper 是一个用于在Flutter应用中集成HelpShift SDK的插件。通过这个插件,你可以在几个简单的步骤内将HelpShift的功能集成到你的Flutter应用中。

快速集成

只需替换 example/lib/src/constants.dart 文件中的以下参数,使用你在HelpShift仪表板中获取的 domainapi_keyapp_id

import 'dart:io';

class Constants {
  static const helpShiftDomain = 'your_helpshift_domain';
  static helpShiftApiKey() {
    if (Platform.isAndroid) {
      return 'your_api_key_for_android';
    } else if (Platform.isIOS) {
      return "your_api_key_for_iOS";
    } else {
      return "";
    }
  }

  static helpShiftAppId() {
    if (Platform.isAndroid) {
      return 'your_app_id_for_android';
    } else if (Platform.isIOS) {
      return "your_app_id_for_iOS";
    } else {
      return "";
    }
  }
}

示例代码

主入口文件 main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:helpshift_wrapper/helpshift_wrapper.dart';
import 'package:helpshift_wrapper_example/src/constants.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  setupHelpShiftSdk();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(const MyApp());
  });
}

/// 配置 HelpShift SDK 以支持原生平台
void setupHelpShiftSdk() async {
  await HelpshiftWrapper.setUpHelpShiftSDK(
    helpShiftApiKey: Constants.helpShiftApiKey(),
    helpShiftAppId: Constants.helpShiftAppId(),
    helpShiftDomain: Constants.helpShiftDomain,
  );
}

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

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

class _MyAppState extends State<MyApp> {
  final userNameCtrl = TextEditingController();
  final userIdCtrl = TextEditingController();
  final userEmailCtrl = TextEditingController();
  var isLoggedIn = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('HelpShift Wrapper'),
          centerTitle: true,
          actions: isLoggedIn
              ? [
                  InkWell(
                    onTap: () async {
                      var result = await HelpshiftWrapper.logoutUser();
                      if (result == true) {
                        setState(() {
                          isLoggedIn = false;
                        });
                      }
                    },
                    child: const Icon(Icons.logout),
                  )
                ]
              : [],
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              isLoggedIn == false
                  ? loginWidget(context)
                  : const SizedBox.shrink(),
              const SizedBox(height: 20),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: ElevatedButton(
                  onPressed: () {
                    HelpshiftWrapper.showAllConversation(
                        configMap: getConfigmap());
                  },
                  child: const Text('Show All Conversation'),
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.showAllConversation(
                      configMap: setMetadata());
                },
                child: const Text('Show All Conversation with Metadata'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openFAQsScreen(configMap: setMetadata());
                },
                child: const Text('FAQs'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openSingleFAQScreen(
                      sectionId: "1", configMap: getConfigmap());
                },
                child: const Text('Order FAQs'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openSingleFAQScreen(
                      sectionId: "2", configMap: getConfigmap());
                },
                child: const Text('Returns and Exchanges FAQs'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openSingleFAQScreen(
                      sectionId: "3", configMap: getConfigmap());
                },
                child: const Text('Shipping and Delivery FAQs'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openSingleFAQScreen(
                      sectionId: "4", configMap: getConfigmap());
                },
                child: const Text('Payment FAQs'),
              ),
              ElevatedButton(
                onPressed: () {
                  HelpshiftWrapper.openSinglePublishedFAQDetail(
                      publishId: "8", configMap: getConfigmap());
                },
                child: const Text('What Payment Methods do you accept?'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  loginWidget(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.all(
          Radius.circular(10),
        ),
        border: Border.all(
          color: Colors.grey,
        ),
      ),
      child: Column(
        children: [
          const SizedBox(height: 30),
          nameLabelUiWidget("User Name", userNameCtrl, TextInputType.name),
          const SizedBox(height: 20),
          nameLabelUiWidget("User Id", userIdCtrl, TextInputType.text),
          const SizedBox(height: 20),
          nameLabelUiWidget(
              "User Email", userEmailCtrl, TextInputType.emailAddress),
          const SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10),
            width: double.infinity,
            child: ElevatedButton(
                onPressed: () async {
                  var userName = userNameCtrl.text.trim();
                  var userId = userIdCtrl.text.trim();
                  var userEmail = userEmailCtrl.text.trim();
                  dynamic result;
                  if (validationUserDetail(context)) {
                    result = await HelpshiftWrapper.loginUser(
                      userId: userId ?? "",
                      email: userEmail ?? "",
                      userName: userName ?? "",
                    );
                  }

                  userNameCtrl.clear();
                  userIdCtrl.clear();
                  userEmailCtrl.clear();

                  if (kDebugMode) {
                    print('result $result');
                  }
                  if (result == true) {
                    setState(() {
                      isLoggedIn = true;
                    });
                  }
                },
                child: const Text('Login')),
          )
        ],
      ),
    );
  }

  nameLabelUiWidget(label, ctrl, inputType) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label),
          const SizedBox(height: 10),
          SizedBox(
            height: 50,
            width: double.infinity,
            child: TextField(
              controller: ctrl,
              keyboardType: inputType,
              decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  filled: true,
                  hintStyle: TextStyle(color: Colors.grey[800]),
                  hintText: "Type in your $label",
                  fillColor: Colors.white70),
            ),
          ),
        ],
      ),
    );
  }

  /// 设置配置映射
  getConfigmap() {
    var config = {};
    // 设置标签用于跟踪
    config["tags"] = ["foo", "bar"];

    // 设置自定义问题字段
    var cifMap = {};
    var isPro = {};
    isPro["type"] = "boolean";
    isPro["value"] = "true";
    cifMap["is_pro"] = isPro;

    config["customIssueFields"] = cifMap;

    return config;
  }

  /// 设置自定义问题字段映射
  getCustomIssueFieldMap() {
    var joiningDate = {};
    joiningDate["type"] = "date";
    joiningDate["value"] = 1505927361535;

    var stockLevel = {};
    stockLevel["type"] = "number";
    stockLevel["value"] = "1505";

    var employeeName = {};
    employeeName["type"] = "singleline";
    employeeName["value"] = "Bugs helpshift";

    var isPro = {};
    isPro["type"] = "boolean";
    isPro["value"] = "true";

    var cifMap = {};
    cifMap["joining_date"] = joiningDate;
    cifMap["stock_level"] = stockLevel;
    cifMap["employee_name"] = employeeName;
    cifMap["is_pro"] = isPro;

    var config = {};
    config["customIssueFields"] = cifMap;

    return config;
  }

  /// 自定义元数据
  setMetadata() {
    var config = {};
    var metaMap = {"usertype": "paid"};
    config["customMetadata"] = metaMap;
    return config;
  }

  /// 验证用户详细信息
  validationUserDetail(BuildContext context) {
    var userId = userIdCtrl.text.trim();
    var userEmail = userEmailCtrl.text.trim();
    if (userId.isEmpty && userEmail.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter userId or email to login.');
      return false;
    } else {
      return true;
    }
  }
}

说明

  1. 初始化:在 main 函数中调用 setupHelpShiftSdk 方法来初始化HelpShift SDK。
  2. 登录:提供了一个登录表单,用户可以输入用户名、用户ID和电子邮件进行登录。
  3. 显示对话:提供了多个按钮,用于显示所有对话、特定部分的FAQ以及单个发布的FAQ详情。
  4. 配置:可以通过 getConfigmapsetMetadata 方法设置自定义配置和元数据。

通过以上步骤,你可以在Flutter应用中快速集成HelpShift客户服务功能。希望这个示例对你有所帮助!


更多关于Flutter客户服务插件helpshift_wrapper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter客户服务插件helpshift_wrapper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用helpshift_wrapper插件来集成Helpshift客户服务功能的示例代码。这个示例将展示如何初始化插件、显示帮助中心和配置用户信息。

首先,确保你已经在pubspec.yaml文件中添加了helpshift_wrapper依赖:

dependencies:
  flutter:
    sdk: flutter
  helpshift_wrapper: ^最新版本号  # 请替换为实际的最新版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤进行配置和使用:

1. 初始化Helpshift

在你的MainApplication(对于Android)或AppDelegate(对于iOS)中进行Helpshift的初始化。不过,由于helpshift_wrapper插件通常会自动处理这些初始化步骤,你可能只需要在Dart代码中配置即可。

2. Dart代码配置

在你的main.dart或相应的初始化文件中,进行如下配置:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化Helpshift
    _initHelpshift();

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }

  void _initHelpshift() async {
    // 替换为你的Helpshift Domain, App ID, 和 API Key
    final String domain = "your_helpshift_domain";
    final String appId = "your_app_id";
    final String apiKey = "your_api_key";

    // 设置用户信息(可选)
    final Map<String, dynamic> userInfo = {
      "userId": "user_12345",  // 用户ID
      "email": "user@example.com",  // 用户邮箱
      "name": "John Doe",  // 用户姓名
      // 可以添加更多自定义字段
    };

    // 初始化Helpshift
    await HelpshiftWrapper.init(
      domain: domain,
      appId: appId,
      apiKey: apiKey,
      userInfo: userInfo,
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Helpshift Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Press the button to open Help Center',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 打开Help Center
                HelpshiftWrapper.showHelpCenter();
              },
              child: Text('Open Help Center'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 处理用户交互

在上述代码中,当用户点击按钮时,会调用HelpshiftWrapper.showHelpCenter()方法来显示Help Center。

4. 处理用户注销或重新登录

如果应用中有用户注销或重新登录的功能,你可能需要在注销时清除Helpshift的用户信息,并在重新登录时重新设置。例如:

void _logout() async {
  // 清除Helpshift的用户信息
  await HelpshiftWrapper.clearUserInfo();
  // 执行其他注销逻辑
}

void _login(String userId, String email, String name) async {
  // 设置新的用户信息
  final Map<String, dynamic> userInfo = {
    "userId": userId,
    "email": email,
    "name": name,
    // 可以添加更多自定义字段
  };
  await HelpshiftWrapper.setUserInfo(userInfo);
  // 执行其他登录逻辑
}

通过上述步骤,你应该能够在Flutter项目中成功集成和使用Helpshift客户服务功能。确保替换代码中的占位符(如your_helpshift_domainyour_app_idyour_api_key)为你的实际Helpshift配置信息。

回到顶部