Flutter ChatBotApp Part-2에서 화웨이 클라우드 기능을 챗봇 서비스로 사용하기

소개
이 기사에서는 Huawei Cloud Functions 서비스를 Flutter의 ChatBotApp에서 Chatbot 서비스로 사용하는 방법에 대해 알아봅니다. Cloud Functions는 서버리스 컴퓨팅을 지원합니다.
서비스 로직을 함수로 분할하여 앱 개발 및 O&M을 단순화하는 FaaS(Function as a Service) 기능을 제공하고, 앱 기능을 보다 쉽게 구현할 수 있도록 Cloud DB 및 Cloud Storage와 연동되는 Cloud Functions SDK를 제공합니다. Cloud Functions는 실제 트래픽을 기반으로 기능을 자동으로 확장 또는 축소하여 서버 리소스 관리에서 벗어나 비용을 절감할 수 있도록 도와줍니다.
주요 기능

주요 컨셉

서비스 작동 방식
Cloud Functions를 사용하려면 AppGallery Connect에서 특정 서비스 기능을 구현할 수 있는 클라우드 기능을 개발하고 이에 대한 트리거(예: HTTP 요청에 대한 HTTP 트리거, Cloud DB 통합 후 데이터 삭제 또는 삽입 요청에 대한 Cloud DB 트리거)를 추가해야 합니다. . Cloud Functions SDK를 통합한 앱이 특정 함수 트리거 조건을 충족하면 앱에서 클라우드 함수를 호출할 수 있으므로 서비스 함수 구축이 크게 용이해집니다.

플랫폼 지원

개발 개요
IDE에 Flutter 및 Dart 플러그인을 설치해야 하며 Flutter 및 Dart에 대한 사전 지식이 있다고 가정합니다.
하드웨어 요구 사항
Windows 10을 실행하는 컴퓨터(데스크탑 또는 노트북).
디버깅에 사용되는 Android 휴대폰(USB 케이블 포함).
소프트웨어 요구 사항
통합 프로세스
1단계: Flutter 프로젝트를 만듭니다.


2단계: 앱 수준 Gradle 종속성을 추가합니다. 내부 프로젝트 Android > 앱 > build.gradle을 선택합니다.
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
루트 수준 Gradle 종속성maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
3단계: Android Manifest 파일에 아래 권한을 추가합니다.
<uses-permission android:name="android.permission.INTERNET" />
4단계: 다운로드한 파일을 프로젝트의 상위 디렉토리에 추가합니다. 종속성 아래의 pubspec.yaml 파일에서 플러그인 경로를 선언합니다.
자산 이미지의 경로 위치를 추가합니다.


이전 기사
Using Huawei Cloud Functions as Chatbot Service in Flutter ChatBotApp Part-1
코딩을 시작하자
메인 다트
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ChatBotService',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'ChatBotService'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isLoggedIn = false;
String str = 'Login required';
final HMSAnalytics _hmsAnalytics = new HMSAnalytics();
List<String> gridItems = ['Email Service', 'Call Center', 'FAQ', 'Chat Now'];
@override
void initState() {
_enableLog();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Visibility(
visible: true,
child: Card(
child: Padding(
padding: EdgeInsets.all(20),
child: Text(
str,
style: const TextStyle(color: Colors.teal, fontSize: 22),
),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if (!isLoggedIn) {
setState(() {
isLoggedIn = true;
signInWithHuaweiID();
});
print('$isLoggedIn');
} else {
setState(() {
isLoggedIn = false;
signOutWithID();
});
print('$isLoggedIn');
}
},
tooltip: 'Login/Logout',
child: isLoggedIn ? const Icon(Icons.logout) : const Icon(Icons.login),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void signInWithHuaweiID() async {
try {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
Future<AuthAccount> account = AccountAuthService.signIn();
account.then(
(value) => setLoginSuccess(value),
);
} on Exception catch (e) {
print(e.toString());
}
}
Future<void> _enableLog() async {
_hmsAnalytics.setUserId("ChatBotServiceApp");
await _hmsAnalytics.enableLog();
}
void setLoginSuccess(AuthAccount value) {
setState(() {
str = 'Welcome ' + value.displayName.toString();
});
showToast(value.displayName.toString());
print('Login Success');
}
Future<void> signOutWithID() async {
try {
final bool result = await AccountAuthService.signOut();
if (result) {
setState(() {
str = 'Login required';
showToast('You are logged out.');
});
}
} on Exception catch (e) {
print(e.toString());
}
}
Future<void> showToast(String name) async {
Fluttertoast.showToast(
msg: "$name",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.lightBlue,
textColor: Colors.white,
fontSize: 16.0);
}
}
ChatPage.dart
class ChatPage extends StatefulWidget {
const ChatPage({Key? key}) : super(key: key);
@override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
List<types.Message> _messages = [];
final _user = const types.User(id: '06c33e8b-e835-4736-80f4-63f44b66666c');
final _bot = const types.User(id: '06c33e8b-e835-4736-80f4-63f54b66666c');
void _addMessage(types.Message message) {
setState(() {
_messages.insert(0, message);
});
}
void _handleSendPressed(types.PartialText message) {
final textMessage = types.TextMessage(
author: _user,
createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(),
text: message.text,
);
_addMessage(textMessage);
callCloudFunction2(message.text);
}
void _loadMessages() async {
final response = await rootBundle.loadString('assets/messages.json');
final messages = (jsonDecode(response) as List)
.map((e) => types.Message.fromJson(e as Map<String, dynamic>))
.toList();
setState(() {
_messages = messages;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Chat(
messages: _messages,
onAttachmentPressed: null,
onMessageTap: null,
onPreviewDataFetched: null,
onSendPressed: _handleSendPressed,
user: _user,
),
);
}
Future<void> callCloudFunction2(String msg) async {
try {
RequestData data = RequestData(msg);
List<Map<String, Object>> params = <Map<String, Object>>[data.toMap()];
var input = data.toMap();
FunctionCallable functionCallable =
FunctionCallable('test-funnel-\$latest');
FunctionResult functionResult = await functionCallable.call(input);
print("Input " + input.toString());
var result = functionResult.getValue();
final textMessage = types.TextMessage(
author: _bot,
createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(),
text: jsonDecode(result)['response'].toString(),
);
_addMessage(textMessage);
} on PlatformException catch (e) {
print(e.message);
}
}
}
핸들러.js
let myHandler = function(event, context, callback, logger) {
try {
var _body = JSON.parse(event.body);
var reqData = _body.message;
var test = '';
if(reqData == '1'){
test = "Thank you for choosing, you will get callback in 10 min.";
}else if(reqData == '2'){
test = "Please click on the link https://feedback.com/myfeedback";
}else if(reqData == '3'){
test = "Please click on the link https://huawei.com/faq";
}
else if(reqData == 'Hi'){
test = " Welcome to ChatBot Service.";
}else{
test = "Enter 1. For call back. 2. For send feedback. 3. For FAQ ";
}
let res = new context.HTTPResponse({"response": test}, {
"res-type": "simple example",
"faas-content-type": "json"
}, "application/json", "200");
logger.info("Response : "+JSON.stringify(res));
callback(res);
} catch (error) {
let res = new context.HTTPResponse({"response": error}, {
"res-type": "simple example",
"faas-content-type": "json"
}, "application/json", "300");
callback(res);
}
};
module.exports.myHandler = myHandler;
결과


트릭과 팁
agconnect-services.json 파일이 추가되었는지 확인합니다.
종속성이 yaml 파일에 추가되었는지 확인하십시오.
종속성을 추가한 후 flutter pug get을 실행합니다.
agc에서 서비스가 활성화되어 있는지 확인하십시오.
이미지가 yaml 파일에 정의되어 있는지 확인합니다.
결론
이 기사에서는 Flutter ChatBotApp에서 Cloud Functions를 사용하여 Huawei 계정 키트, 분석 키트 및 ChatBot 기능을 통합하는 방법을 배웠습니다. 계정 키트가 통합되면 사용자는 초기 액세스 권한을 부여한 후 Huawei ID로 빠르고 편리하게 앱에 로그인할 수 있습니다.
읽어주셔서 정말 감사합니다. 이 기사가 Flutter ChatBotApp에서 Huawei 계정 키트, 분석 키트 및 Huawei Cloud Functions의 통합을 이해하는 데 도움이 되기를 바랍니다.
참조
Cloud Functions
Training Videos
Checkout in forum
Reference
이 문제에 관하여(Flutter ChatBotApp Part-2에서 화웨이 클라우드 기능을 챗봇 서비스로 사용하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/hmscommunity/using-huawei-cloud-functions-as-chatbot-service-in-flutter-chatbotapp-part-2-48an텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)