Integration of Huawei Account kit and Analytics kit in Flutter DietApp – Part 1
Tags: huaweiaccountkit, huaweianalyicskit, hmscore, appgallery
Published: 2022-03-15 11:26:03

**Introduction**

In this article, we will be integrating Huawei Account and Analytics kit in Flutter DietApp. Flutter plugin provides simple and convenient way to experience authorization of users. Flutter Account Plugin allows users to connect to the Huawei ecosystem using their Huawei IDs from the different devices such as mobiles phones and tablets, added users can login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission.

Huawei Analytics is a one-stop solution to get user behaviour analysis in different platforms for all yours products such as mobile apps, web apps and quick apps. It helps developers to get detailed analysis report and also provides crash reports by default. It offers scenario-specific data collection, management, analysis, and usage, helping enterprises to achieve effective user acquisition, product optimization, precise operations, and business growth.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubdjldu9rtowvo8wsy57.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrxbb37j9kqvy7sizn5s.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/r244acv2calw0s8f57xh.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqr994znx2c2rclwrphi.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 4: Download flutter plugins

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/dhlldcr9vk7qym2ufjmz.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dozrd4wt6ucxaueqajlj.png)

**Let's start coding**  

**loginScreen.dart**

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LoginDemo(),
    );
  }
}
class LoginDemo extends StatefulWidget {
  @override
  _LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
  final HMSAnalytics _hmsAnalytics = new HMSAnalytics();
  @override
  void initState() {
    _enableLog();
    super.initState();
  }
  Future<void> _enableLog() async {
    _hmsAnalytics.setUserId("TestUserDietApp");
    await _hmsAnalytics.enableLog();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Login"),
        backgroundColor: Colors.grey[850],
      ),
      body: RefreshIndicator(
        onRefresh: showToast,
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(top: 90.0),
                child: Center(
                  child: Container(
                      width: 220,
                      height: 165,
                      decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(60.0)),
                      child: Image.asset('images/logo_huawei.png')),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(
                    left: 40.0, right: 40.0, top: 15, bottom: 0),
                child: TextField(
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Email',
                      hintText: 'Enter valid email id '),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    left: 40.0, right: 40.0, top: 10, bottom: 0),
                child: TextField(
                  obscureText: true,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Password',
                      hintText: 'Enter password'),
                ),
              ),
              FlatButton(
                onPressed: () {
                },
                child: Text(
                  'Forgot Password',
                  style: TextStyle(color: Colors.blue, fontSize: 15),
                ),
              ),
              Container(
                height: 50,
                width: 270,
                decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(20)),
                child: FlatButton(
                  onPressed: () async {
                    try {
                      try {
                        final bool result = await AccountAuthService.signOut();
                        if (result) {
                          final bool response =
                              await AccountAuthService.cancelAuthorization();
                        }
                      } on Exception catch (e) {
                        print(e.toString());
                      }
                    } on Exception catch (e) {
                      print(e.toString());
                    }
                  },
                  child: GestureDetector(
                    onTap: () async {
                      try {
                        final bool response =
                            await AccountAuthService.cancelAuthorization();
                      } on Exception catch (e) {
                        print(e.toString());
                      }
                    },
                    child: Text(
                      'Login',
                      style: TextStyle(color: Colors.white, fontSize: 22),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Container(
                height: 50,
                width: 270,
                decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(5)),
                child: HuaweiIdAuthButton(
                    theme: AuthButtonTheme.FULL_TITLE,
                    buttonColor: AuthButtonBackground.RED,
                    borderRadius: AuthButtonRadius.MEDIUM,
                    onPressed: () {
                      signInWithHuaweiID();
                    }),
              ),
              SizedBox(
                height: 30,
              ),
             
            ],
          ),
        ),
      ),
    );
  }
  void signInWithHuaweiID() async {
    AccountAuthParamsHelper helper = new AccountAuthParamsHelper();
    String name = '';
    helper.setAuthorizationCode();
    try {
      Future<AuthAccount> account = AccountAuthService.signIn();
      account.then((value) => Navigator.push(
          context,
          MaterialPageRoute(
              builder: (_) => MyHomePage(
                    title: '' + value.displayName.toString(),
                  ))));
    } on Exception catch (e) {
      print(e.toString());
    }
  }

  Future<void> showToast() async {
    Fluttertoast.showToast(
        msg: "Refreshing.. ",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.lightBlue,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}

```
**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: 'Exercise&DietApp',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SplashScreen(),
    );
  }
}
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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Wel come ',
            ),
            Text(
              widget.title.toString(),
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
  }
}

```
**Result**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z221dxck6d9zuhgv47cs.gif)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy62hgfmf0mno9wlxn4f.png)

**Tricks and Tips**

Make sure that downloaded plugin is unzipped in parent directory of project.
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 in Flutter DietApp. Once Account kit integrated, users can login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission.

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

**Reference**

[Account Kit](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050766441) 
[Training Video](https://developer.huawei.com/consumer/en/training/course/video/101584324766101108) 
[Checkout in forum](https://forums.developer.huawei.com/forumPortal/en/topic/0202823786262120048?fid=0101187876626530001?ha_source=hms1)