Using Huawei Cloud Functions as Chatbot Service in Flutter ChatBotApp Part-1
Tags: huaweiaccoutkit, huaweianalyticskit, huaweicloudfunctions, dart
Published: 2022-04-27 12:25:44

 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2hciigrjxpjwfc2pin43.png)
**Introduction**

In this article, we will learn how to make use of Huawei Cloud Functions service as Chatbot service in ChatBotApp in flutter. Cloud Functions enables serverless computing. It provides the Function as a Service (FaaS) capabilities to simplify app development and O&M by splitting service logic into functions and offers the Cloud Functions SDK that works with Cloud DB and Cloud Storage so that your app functions can be implemented more easily. Cloud Functions automatically scales in or out functions based on actual traffic, freeing you from server resource management and helping you reduce costs.

**Key Functions**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyfkmm7l24mow1egjw2e.png)
**Key Concepts**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srgtmq62i22cdolx2sxj.png)
**How the Service Works**
To use Cloud Functions, you need to develop cloud functions that can implement certain service functions in AppGallery Connect and add triggers for them, for example, HTTP triggers for HTTP requests, and Cloud DB triggers for data deletion or insertion requests after Cloud DB is integrated. After your app that integrates the Cloud Functions SDK meets conditions of specific function triggers, your app can call the cloud functions, which greatly facilitates service function building.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mybcvv7h0b48zl1h3pez.png)
**Platform Support**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvk86pkt5xk8bpax6445.png)
**Development Overview**
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.

**Hardware Requirements**
- A computer (desktop or laptop) running Windows 10.
- Android phone (with the USB cable), which is used for debugging.

**Software Requirements**
- Java JDK 1.7 or later.
- Android studio software or Visual Studio or Code installed.
- HMS Core (APK) 4.X or later.

**Integration process**

**Step 1:** Create Flutter project.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yotv6783xnl0bdrkji5b.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jexx5yynq096jg05scm1.png)
**Step 2:** Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.

```
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
```
Root level gradle dependencies

```
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
```
**Step 3:** Add the below permissions in Android Manifest file.
`<uses-permission android:name="android.permission.INTERNET" />`
**Step 5:** Add downloaded file into parent directory of the project. Declare plugin path in pubspec.yaml file under dependencies.

Add path location for asset image.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4vbft78995c6i5u0obb.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i8cla3bqql0ciur8ict.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mrfpsah370m9r4ftbjhn.PNG)
Let's start coding

main.dart

```
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);
  }
}

```
**Result**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1a8c9qo3ckpnv2226fs.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1b8umga0p6cw0rc263k.gif)
**Tricks and Tips**
Makes sure that agconnect-services.json file added.
Make sure dependencies are added yaml file.
Run flutter pug get after adding dependencies.
Make sure that service is enabled in agc.
Makes sure images are defined in yaml file.

**Conclusion**
In this article, we have learnt how to integrate Huawei Account kit, analytics kit in flutter ChatBotApp. Once Account kit integrated, users can login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission. In part-2 we will learn the actual Cloud Functions as Chatbot service.

Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit and Analytics kit in flutter ChatBotApp.

**Reference**
[Cloud Functions](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-cloudfunction-introduction-0000001059279544)
[Checkout in forum](https://forums.developer.huawei.com/forumPortal/en/topic/0202860006325440216?fid=0101188387844930001)