Flutter自定义功能插件hs_wrapper的使用
Flutter 自定义功能插件 hs_wrapper
的使用
简介
hs_wrapper
是一个用于 Flutter 应用程序的新插件项目。它包含适用于 Android 和/或 iOS 平台的特定平台实现代码。
开始使用
要开始使用此插件,首先需要确保你的 Flutter 环境已经设置好,并且你可以创建一个新的 Flutter 项目。
完整示例
以下是一个完整的示例,展示了如何在 Flutter 应用程序中使用 hs_wrapper
插件。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hs_wrapper/hs_wrapper.dart';
import 'package:hs_wrapper_example/src/constants.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
setupHelpShiftSdk();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(const MyApp());
});
}
/// 配置 HelpShift SDK 用于原生平台
void setupHelpShiftSdk() async {
await HsWrapper.setUpHelpShiftSDK(
helpShiftApiKey: Constants.helpShiftApiKey(),
helpShiftAppId: Constants.helpShiftAppId(),
helpShiftDomain: Constants.helpShiftDomain,
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final userNameCtrl = TextEditingController();
final userIdCtrl = TextEditingController();
final userEmailCtrl = TextEditingController();
var isLoggedIn = false;
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Hs Wrapper'),
centerTitle: true,
actions: isLoggedIn
? [
InkWell(
onTap: () async {
var result = await HsWrapper.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: () {
HsWrapper.showAllConversation(
configMap: getConfigmap());
},
child: const Text('显示所有对话'),
),
),
const SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () {
HsWrapper.showAllConversation(
configMap: setMetadata());
},
child: const Text('显示所有对话'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openFAQsScreen(configMap: setMetadata());
},
child: const Text('常见问题'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openSingleFAQScreen(
sectionId: "1", configMap: getConfigmap());
},
child: const Text('订单常见问题'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openSingleFAQScreen(
sectionId: "2", configMap: getConfigmap());
},
child: const Text('退货与换货常见问题'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openSingleFAQScreen(
sectionId: "3", configMap: getConfigmap());
},
child: const Text('配送与发货常见问题'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openSingleFAQScreen(
sectionId: "4", configMap: getConfigmap());
},
child: const Text('支付常见问题'),
),
ElevatedButton(
onPressed: () {
HsWrapper.openSinglePublishedFAQDetail(
publishId: "8", configMap: getConfigmap());
},
child: const Text('你们接受哪些支付方式?'),
),
],
),
),
),
);
}
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("用户名", userNameCtrl, TextInputType.name),
const SizedBox(height: 20),
nameLabelUiWidget("用户ID", userIdCtrl, TextInputType.text),
const SizedBox(height: 20),
nameLabelUiWidget(
"用户邮箱", 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 HsWrapper.loginUser(
userId: userId ?? "",
email: userEmail ?? "",
userName: userName ?? "",
);
}
userEmailCtrl.clear();
userIdCtrl.clear();
userNameCtrl.clear();
if (kDebugMode) {
print('result $result');
}
if (result == true) {
setState(() {
isLoggedIn = true;
});
}
},
child: const Text('登录')),
)
],
),
);
}
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: "输入您的 $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: '请输入用户ID或邮箱以登录。');
return false;
} else {
return true;
}
}
}
更多关于Flutter自定义功能插件hs_wrapper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter自定义功能插件hs_wrapper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中创建和使用自定义功能插件hs_wrapper
的示例代码。这个示例将展示如何创建一个简单的插件,该插件在原生代码(Android和iOS)中执行一些操作,并通过Dart代码进行调用。
1. 创建Flutter插件项目
首先,使用Flutter命令行工具创建一个新的插件项目:
flutter create --template=plugin hs_wrapper
这将创建一个名为hs_wrapper
的Flutter插件项目。
2. 修改pubspec.yaml
在hs_wrapper/example/pubspec.yaml
文件中,添加对hs_wrapper
插件的依赖:
dependencies:
flutter:
sdk: flutter
hs_wrapper:
path: ../
3. 实现原生功能
Android端实现
在hs_wrapper/android/src/main/java/com/example/hs_wrapper/HsWrapperPlugin.java
文件中,实现一个简单的原生方法:
package com.example.hs_wrapper;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import android.app.Activity;
import android.os.Bundle;
public class HsWrapperPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
private MethodChannel channel;
private Activity activity;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "hs_wrapper");
channel.setMethodCallHandler(this);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if (call.method.equals("getGreeting")) {
String greeting = getGreetingFromNative();
result.success(greeting);
} else {
result.notImplemented();
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
activity = binding.getActivity();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
activity = null;
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
activity = binding.getActivity();
}
@Override
public void onDetachedFromActivity() {
activity = null;
}
private String getGreetingFromNative() {
return "Hello from Native Android!";
}
}
iOS端实现
在hs_wrapper/ios/Classes/HsWrapperPlugin.swift
文件中,实现相应的原生方法:
import Flutter
public class HsWrapperPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterRegistrar) {
let channel = FlutterMethodChannel(name: "hs_wrapper", binaryMessenger: registrar.messenger())
let instance = HsWrapperPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getGreeting" {
let greeting = getGreetingFromNative()
result(greeting)
} else {
result(FlutterMethodNotImplemented)
}
}
private func getGreetingFromNative() -> String {
return "Hello from Native iOS!"
}
}
4. 在Flutter中使用插件
在hs_wrapper/example/lib/main.dart
文件中,调用插件提供的方法:
import 'package:flutter/material.dart';
import 'package:hs_wrapper/hs_wrapper.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('hs_wrapper Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _getGreeting,
child: Text('Get Greeting'),
),
),
),
);
}
Future<void> _getGreeting() async {
String greeting;
try {
greeting = await HsWrapper.getGreeting();
} catch (e) {
greeting = 'Failed to get greeting: ${e.message}';
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(greeting)),
);
}
}
在hs_wrapper/lib/hs_wrapper.dart
文件中,定义与原生代码交互的接口:
import 'dart:async';
import 'package:flutter/services.dart';
class HsWrapper {
static const MethodChannel _channel = MethodChannel('hs_wrapper');
static Future<String> getGreeting() async {
final String result = await _channel.invokeMethod('getGreeting');
return result;
}
}
5. 运行示例应用
确保你已经连接了Android模拟器或iOS模拟器,然后在hs_wrapper/example
目录下运行Flutter应用:
flutter run
现在,你应该能够看到一个按钮,点击后会显示从原生代码返回的问候语。
这个示例展示了如何创建一个简单的Flutter插件,并在Dart代码中调用原生方法。你可以根据需要扩展这个插件,添加更多的原生功能和更复杂的交互。