Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

Integration of Huawei Account kit, Remote Configuration Service and Crash kit in Flutter DietApp – Part 5

Introduction

On this article, we will probably be integrating Huawei Distant Configuration service, Account Equipment in Flutter DietApp. Flutter plugin supplies easy and handy technique to expertise authorization of customers. Flutter Account Plugin permits customers to connect with the Huawei ecosystem utilizing their Huawei IDs from the completely different gadgets similar to mobiles telephones and tablets, added customers can login shortly and conveniently sign up to apps with their Huawei IDs after granting preliminary entry permission.

We can even be taught to combine Huawei Crash Service on this software. It’s a accountability of the developer to construct crash free i.e. surprising exit of software, it is vitally tough to search out the reason for the crash in large software code base. This surprising crash makes app customers annoying and will result in enterprise loss and cut back market worth of the product and the corporate. To keep away from such crashes Huawei supplies Crash service which makes developer to search out the crash and reason for surprising exit of the appliance in AG-console.

Crash SDK supplies quite simple and developer needn’t code a lot to implementation crash service. It’s also possible to obtain the detailed crash report each time required.

Distant Configuration is a service offered by Huawei. It supplies cloud-based companies. When you combine the shopper SDK, your app can periodically fetch parameter values from the cloud. The service checks whether or not the parameter that your app tries fetching has an on-cloud worth replace and returns the brand new worth in that case. Based mostly on the parameter values fetched, you possibly can implement service processing logic to vary behaviour or look of your app. On this pattern i.e. DietApp, we’re fetching the Private Train knowledge utilizing Distant Configuration service by AppGallery.

Earlier article

Please verify my earlier articles, in case you have not gone by, click on on part-4.

Improvement Overview

It’s essential set up Flutter and Dart plugin in IDE and I assume that you’ve prior information concerning the Flutter and Dart.

{Hardware} Necessities

A pc (desktop or laptop computer) working Home windows 10.
Android cellphone (with the USB cable), which is used for debugging.
Software program Necessities

Java JDK 1.7 or later.
Android studio software program or Visible Studio or Code put in.
HMS Core (APK) 4.X or later.
Integration course of

Step 1: Create Flutter venture.
Image description
Image description
Step 2: Add the App stage gradle dependencies. Select inside venture Android > app > construct.gradle.

apply plugin: 'com.android.software'
apply plugin: 'com.huawei.agconnect'
Enter fullscreen mode

Exit fullscreen mode

Root stage gradle dependencies

maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
Enter fullscreen mode

Exit fullscreen mode

Step 3: Add the under permissions in Android Manifest file.
<uses-permission android:identify="android.permission.INTERNET" />

Step 4: Add downloaded file into dad or mum listing of the venture. Declare plugin path in pubspec.yaml file underneath dependencies.

Add path location for asset picture.
Image description
Image description
Let’s begin coding

SplashScreen.dart

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    tremendous.initState();
    Timer(
        Length(seconds: 3),
        () => Navigator.pushReplacement(context,
            MaterialPageRoute(builder: (context) => const LoginScreen())));
  }

  @override
  Widget construct(BuildContext context) {
    return Container(
        shade: Colours.white, little one: Picture.asset('photos/logo_huawei.png'));
  }
}

Enter fullscreen mode

Exit fullscreen mode

loginScreen.dart

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

  @override
  Widget construct(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      dwelling: LoginDemo(),
    );
  }
}

class LoginDemo extends StatefulWidget {
  @override
  _LoginDemoState createState() => _LoginDemoState();
}

class _LoginDemoState extends State<LoginDemo> {
  ultimate HMSAnalytics _hmsAnalytics = new HMSAnalytics();
  @override
  void initState() {
    _enableLog();
    tremendous.initState();
  }

  Future<void> _enableLog() async {
    _hmsAnalytics.setUserId("TestUserDietApp");
    await _hmsAnalytics.enableLog();
  }

  @override
  Widget construct(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.white,
      appBar: AppBar(
        title: Textual content("Login"),
        backgroundColor: Colours.blue,
      ),
      physique: RefreshIndicator(
        onRefresh: showToast,
        little one: SingleChildScrollView(
          little one: Column(
            kids: <Widget>[
              Padding(
                padding: const EdgeInsets.only(top: 90.0),
                child: Center(
                  child: Container(
                      width: 320,
                      height: 220,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(50.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: () {
                  //TODO FORGOT PASSWORD SCREEN GOES HERE
                },
                child: Text(
                  'Forgot Password',
                  style: TextStyle(color: Colors.blue, fontSize: 15),
                ),
              ),
              Container(
                height: 50,
                width: 270,
                decoration: BoxDecoration(
                    color: Colors.red, 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(borderRadius: BorderRadius.circular(5)),
                child: HuaweiIdAuthButton(
                    theme: AuthButtonTheme.FULL_TITLE,
                    buttonColor: AuthButtonBackground.RED,
                    borderRadius: AuthButtonRadius.MEDIUM,
                    onPressed: () {
                      signInWithHuaweiID();
                    }),
              ),
              SizedBox(
                height: 30,
              ),
              GestureDetector(
                onTap: () {
                  //showBannerAd();
                },
                child: Text('New User? Create Account'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void signInWithHuaweiID() async {
    AccountAuthParamsHelper helper = new AccountAuthParamsHelper();
    String identify="";
    helper.setAuthorizationCode();
    attempt {
      // The sign-in is profitable, and the person's ID data and authorization code are obtained.

      Future<AuthAccount> account = AccountAuthService.signIn();
      account.then(
        (worth) => Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => MyHomePage(
              title: worth.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: Colours.lightBlue,
        textColor: Colours.white,
        fontSize: 16.0);
  }
}

Enter fullscreen mode

Exit fullscreen mode

essential.dart

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

class MyApp extends StatelessWidget {
  // This widget is the basis of your software.
  @override
  Widget construct(BuildContext context) {
    return MaterialApp(
      title: 'Train&DietApp',
      theme: ThemeData(
        primarySwatch: Colours.blue,
      ),
      dwelling: SplashScreen(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : tremendous(key: key);

  ultimate String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late double? age, top, weight, tagetWeight, days;
  TextEditingController ageController = TextEditingController();
  TextEditingController genderController = TextEditingController();
  TextEditingController heightController = TextEditingController();
  TextEditingController weightController = TextEditingController();
  TextEditingController targetWeightController = TextEditingController();
  TextEditingController inDaysWeightController = TextEditingController();
  TextEditingController dietPlanController = TextEditingController();
  TextEditingController activeLevelPlanController = TextEditingController();
  late SharedPreferences prefs;

  String _genderLabel = "Male";
  String _dietLabel = "Veg";
  String _activeLable = "Low-Energetic";
  ultimate _genderList = ["Male", "Women"];
  ultimate _dietPlanList = ["Veg", "Non Veg", "Egg"];
  ultimate _activeLevelList = ["Low-Active", "Mid-Active", "Very Active"];
  String _token = '';

  void initState() {
    initPreferences();
    initTokenStream();
    tremendous.initState();
  }

  Future<void> initTokenStream() async {
    if (!mounted) return;
    Push.getTokenStream.pay attention(_onTokenEvent, onError: _onTokenError);

    getToken();
  }

  void getToken() async {
    // Name this technique to request for a token
    Push.getToken("");
  }

  void _onTokenEvent(String occasion) {
    // Requested tokens will be obtained right here
    setState(() {
      _token = occasion;
      print("TokenEvent: " + _token);
    });
  }

  void _onTokenError(Object error) {
    print("TokenErrorEvent: " + error.toString());
    PlatformException? e = error as PlatformException?;
  }

  @override
  Widget construct(BuildContext context) {
    return SafeArea(
      little one: Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          title: Textual content(widget.title.toString()),
          automaticallyImplyLeading: false,
        ),
        physique: Heart(
          little one: SingleChildScrollView(
            reverse: true,
            little one: Column(
              mainAxisAlignment: MainAxisAlignment.begin,
              kids: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(top: 0.0),
                  child: Center(
                    child: Container(
                        width: 120,
                        height: 120,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(60.0)),
                        child: Image.asset('images/nu_icon.png')),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      left: 22.0, right: 22.0, top: 15, bottom: 0),
                  child: TextField(
                    controller: ageController,
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Age',
                        hintText: 'Enter valid age '),
                  ),
                ),

                Padding(
                  padding: const EdgeInsets.only(
                      left: 22.0, right: 22.0, top: 15, bottom: 0),
                  child: TextField(
                    controller: heightController,
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Height',
                        hintText: 'Enter height '),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      left: 22.0, right: 22.0, top: 15, bottom: 0),
                  child: TextField(
                    controller: weightController,
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Weight',
                        hintText: 'Enter Weight '),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      left: 22.0, right: 22.0, top: 15, bottom: 0),
                  child: TextField(
                    controller: targetWeightController,
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Target Weight',
                        hintText: 'Enter target Weight '),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      left: 22.0, right: 22.0, top: 15, bottom: 0),
                  child: TextField(
                    controller: inDaysWeightController,
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'In days',
                        hintText: 'How quickly you want loose/gain weight '),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    const Text('Gender :'),
                    DropdownButton(
                      items: _genderList
                          .map((String item) => DropdownMenuItem<String>(
                              child: SizedBox(
                                  height: 22,
                                  width: 100,
                                  child: Text(item,
                                      style: TextStyle(fontSize: 20))),
                              value: item))
                          .toList(),
                      onChanged: (value) {
                        setState(() {
                          _genderLabel = value.toString();
                        });
                      },
                      value: _genderLabel,
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  kids: [
                    Text('Diet Plan :'),
                    DropdownButton(
                      items: _dietPlanList
                          .map((String item) => DropdownMenuItem<String>(
                              child: SizedBox(
                                  height: 22,
                                  width: 100,
                                  child: Text(item,
                                      style: TextStyle(fontSize: 20))),
                              value: item))
                          .toList(),
                      onChanged: (value) {
                        setState(() {
                          _dietLabel = value.toString();

                          print('Diet plan changed to   $value');
                        });
                      },
                      value: _dietLabel,
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  kids: [
                    Text('Active Level :'),
                    DropdownButton(
                      items: _activeLevelList
                          .map((String item) => DropdownMenuItem<String>(
                              child: SizedBox(
                                  height: 22,
                                  width: 100,
                                  child: Text(item,
                                      style: TextStyle(fontSize: 20))),
                              value: item))
                          .toList(),
                      onChanged: (value) {
                        setState(() {
                          _activeLable = value.toString();
                          print('Active level changed to   $value');
                        });
                      },
                      value: _activeLable,
                    )
                  ],
                )
                ,
                Padding(
                  padding: const EdgeInsets.solely(
                      left: 22.0, proper: 22.0, high: 20, backside: 0),
                  little one: MaterialButton(
                    little one: const Textual content(
                      'Subsequent',
                      type: TextStyle(
                          fontSize: 22,
                          shade: Colours.white,
                          fontWeight: FontWeight.w300),
                    ),
                    top: 45,
                    minWidth: 140,
                    shade: Colours.lightBlue,
                    form: RoundedRectangleBorder(
                      borderRadius: BorderRadius.round(10.0),
                    ),
                    onPressed: () {
                      print('Button clicked.....');
                      age = double.parse(ageController.textual content);
                      top = double.parse(heightController.textual content);
                      weight = double.parse(weightController.textual content);
                      tagetWeight = double.parse(targetWeightController.textual content);
                      days = double.parse(inDaysWeightController.textual content);

                      storeDataLocally();
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> storeDataLocally() async {
    prefs.setString("identify", widget.title.toString());
    prefs.setDouble("age", age!);
    prefs.setDouble("top", top!);
    prefs.setString("gender", _genderLabel);
    prefs.setDouble("weight", weight!);
    prefs.setString("dietPlan", _dietLabel);
    prefs.setDouble("targetWeight", tagetWeight!);
    prefs.setString("activeLevel", _activeLable);
    prefs.setDouble("inDays", days!);

    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const DietPlanScreen()),
    );
  }

  Future<void> initPreferences() async {
    prefs = await SharedPreferences.getInstance();
    showData();
  }

  void showData() {
    print("Gender ===>" + prefs.getString('gender').toString());
    print("Weight-reduction plan Plan ===>" + prefs.getString('dietPlan').toString());
    print("Energetic Degree ===>" + prefs.getString('activeLevel').toString());
    if (prefs.getDouble('age')! > 10) {
      ageController.textual content = prefs.getDouble('age').toString();
      heightController.textual content = prefs.getDouble('top').toString();
      targetWeightController.textual content = prefs.getDouble('targetWeight').toString();
      genderController.textual content = prefs.getString('gender').toString();
      dietPlanController.textual content = prefs.getString('dietPlan').toString();
      weightController.textual content = prefs.getDouble('weight').toString();
      inDaysWeightController.textual content = prefs.getDouble('inDays').toString();
      activeLevelPlanController.textual content =
          prefs.getString('activeLevel').toString();
      if (prefs.getString('gender').toString() != null &&
          prefs.getString('gender').toString() != '') {
        _genderLabel = prefs.getString('gender').toString();
      }
      if (prefs.getString('dietPlan').toString() != null) {
        _dietLabel = prefs.getString('dietPlan').toString();
      }
      if (prefs.getString('activeLevel').toString() != null) {
        _activeLable = prefs.getString('activeLevel').toString();
      }
    }
  }
}

Enter fullscreen mode

Exit fullscreen mode

tabScreen.dart

class TabScreen extends StatefulWidget {
  @override
  TabScreenPage createState() => TabScreenPage();
}

class TabScreenPage extends State<TabScreen> {
  ultimate rnd = math.Random();
  Record<String> gridItems = [];

  @override
  void initState() {
    // TODO: implement initState
    fetchRemoteConfiguration();
    tremendous.initState();
  }

  @override
  Widget construct(BuildContext context) {
    return DefaultTabController(
      size: 2,
      little one: Scaffold(
        appBar: AppBar(
          title: const Textual content(
            'Weight-reduction plan Plan',
          ),
          centerTitle: true,
          backgroundColor: Colours.blue,
          elevation: 0,
        ),
        physique: Column(
          kids: <Widget>[
            SizedBox(
              height: 50,
              child: AppBar(
                bottom: const TabBar(
                  tabs: [
                    Tab(
                      text: 'Paid Diet Plans',
                    ),
                    Tab(
                      text: 'Personal Exercise',
                    ),
                  ],
                ),
              ),
            ),

            // create widgets for every tab bar right here
            Expanded(
              little one: TabBarView(
                kids: [
                  Container(
                    color: Colors.white,
                    child: ListView(
                      padding: EdgeInsets.all(8),
                      children: <Widget>[
                        Card(
                          child: ListTile(
                            title: Text("30 days plan"),
                            iconColor: Colors.blue,
                            subtitle: Text('Meal Plan: Burn 1,200 Calories'),
                            leading: Icon(Icons.sports_gymnastics),
                            onTap: () {
                              routeScreen('30 days plan');
                            },
                          ),
                        ),
                        Card(
                          child: ListTile(
                            title: Text("28 days plan"),
                            iconColor: Colors.blue,
                            subtitle: Text('Meal Plan: Burn 950 Calories'),
                            leading: Icon(Icons.sports_gymnastics),
                            onTap: () {
                              routeScreen('28 days plan');
                            },
                          ),
                        ),
                        Card(
                          child: ListTile(
                            title: Text("22 days plan"),
                            iconColor: Colors.blue,
                            subtitle: Text('Meal Plan: Burn 850 Calories'),
                            leading: Icon(Icons.sports_gymnastics),
                            onTap: () {
                              routeScreen('22 days plan');
                            },
                          ),
                        ),
                        Card(
                          child: ListTile(
                            iconColor: Colors.blue,
                            title: Text("18 days plan"),
                            subtitle: Text('Meal Plan: Burn 650 Calories'),
                            leading: Icon(Icons.sports_gymnastics),
                            onTap: () {
                              routeScreen('18 days plan');
                            },
                          ),
                        ),
                      ],
                    ),
                  ),

                  Container(
                    shade: Colours.white,
                    little one: Padding(
                      padding: const EdgeInsets.all(8.0),
                      little one: GridView.builder(
                          gridDelegate:
                              const SliverGridDelegateWithMaxCrossAxisExtent(
                                  maxCrossAxisExtent: 200,
                                  childAspectRatio: 3 / 3,
                                  crossAxisSpacing: 20,
                                  mainAxisSpacing: 20),
                          itemCount: gridItems.size,
                          itemBuilder: (BuildContext ctx, index) {
                            return Heart(
                              little one: GestureDetector(
                                onTap: () {
                                  print(' ' + gridItems[index]);
                                },
                                little one: Container(
                                  alignment: Alignment.heart,
                                  little one: Textual content(gridItems[index],
                                      type: const TextStyle(
                                          shade: Colours.white,
                                          fontSize: 24,
                                          fontWeight: FontWeight.daring)),
                                  ornament: BoxDecoration(
                                      shade: Colours.primaries[Random()
                                          .nextInt(Colors.primaries.length)],
                                      borderRadius: BorderRadius.round(15)),
                                ),
                              ),
                            );
                          }),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void routeScreen(String title) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => PaidPlanScreen(title)),
    );
  }

  Future<void> fetchRemoteConfiguration() async {
    await AGCRemoteConfig.occasion
        .fetch()
        .catchError((error) => print(error.toString()));
    await AGCRemoteConfig.occasion.applyLastFetched();
    Map worth = await AGCRemoteConfig.occasion.getMergedAll();
    ultimate knowledge = jsonDecode(worth["categories"].toString());
    Record<String> gridItem = Record<String>.from(knowledge['categories']);
    setState(() {
      gridItems.addAll(gridItem);
    });
  }
}

Enter fullscreen mode

Exit fullscreen mode

Consequence
Image description
Image description
Image description

Image description

Methods and Suggestions

Make it possible for downloaded plugin is unzipped in dad or mum listing of venture.
Makes certain that agconnect-services.json file added.
Make certain dependencies are added yaml file.
Run flutter pug get after including dependencies.
Make it possible for service is enabled in agc.
Makes certain photos are outlined in yaml file.
Make certain parameter added in agc is json format.
Conclusion

On this article, now we have learnt find out how to combine Huawei Distant Configuration service, Account equipment, Crash equipment flutter DietApp. As soon as Account equipment built-in, customers can login shortly and conveniently sign up to apps with their Huawei IDs after granting preliminary entry permission. Push equipment lets you ship push notification to person system in actual time, you possibly can see the push notification within the consequence half. Huawei Crash service which supplies builders to shortly detect, find and repair the crash or surprising exit of software. Therefore improves stability and reliability of software. With the assistance of Distant Configuration service we’re fetching the Private Train knowledge from the cloud.

Thanks a lot for studying. I hope this text lets you perceive the combination of Huawei Distant Configuration, Account equipment and Crash equipment in flutter DietApp.

Reference

Crash Kit

Account Equipment – Training Video

Crash Equipment – Training Video

Remote Configuration

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?