{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Account, Analytics and Ads kit in StoryApp. 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 Ads kit provides access to range of development capabilities. You can promote your apps quickly and more efficiently to Huawei’s vast users. Ads kit helps your app to be monetize quickly and start generating revenue.
Huawei supports following Ads types
Banner
Interstitial
Native
Reward
Splash
Instream(Roll)
Flutter Analytics Plugin provides wider range of predefined analytics models to get more insight into your application users, products, and content. With this insight, you can prepare data-driven approach to market your apps and optimize your products based on the analytics.
With Analytics Kit's on-device data collection SDK, you can:
Collect and report custom events.
Set a maximum of 25 user attributes.
Automate event collection and session calculation.
Pre-set event IDs and parameters.
Restrictions
1. Devices:
a. Analytics Kit depends on HMS Core (APK) to automatically collect the following events: INSTALLAPP (app installation), UNINSTALLAPP (app uninstallation), CLEARNOTIFICATION (data deletion), INAPPPURCHASE (in-app purchase), RequestAd (ad request), DisplayAd (ad display), ClickAd (ad tapping), ObtainAdAward (ad award claiming), SIGNIN (sign-in), and SIGNOUT (sign-out). These events cannot be automatically collected on third-party devices where HMS Core (APK) is not installed (including but not limited to OPPO, vivo, Xiaomi, Samsung, and OnePlus).
b. Analytics Kit does not work on iOS devices.
2. Number of events:
A maximum of 500 events are supported.
3. Number of event parameters:
You can define a maximum of 25 parameters for each event, and a maximum of 100 event parameters for each project.
4. Supported countries/regions
The service is now available only in the countries/regions listed in Supported Countries/Regions.
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.
A Huawei 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.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add the below permissions in Android Manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA"/>
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.
Let's start coding
loginScreen.dart
Code:
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() {
// TODO: implement initState
HwAds.init();
_enableLog();
_predefinedEvent();
showBannerAd();
super.initState();
}
Future<void> _enableLog() async {
_hmsAnalytics.setUserId("TestUserStoryApp");
await _hmsAnalytics.enableLog();
}
void _predefinedEvent() async {
String name = HAEventType.SIGNIN;
dynamic value = {HAParamType.ENTRY: 06534797};
await _hmsAnalytics.onEvent(name, value);
print("Event posted");
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login Page"),
backgroundColor: Colors.grey[850],
),
body: RefreshIndicator(
onRefresh: showToast,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(60.0)),
child: Image.asset('images/logo_huawei.png')),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter valid email id '),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, 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: 25),
),
),
),
),
SizedBox(
height: 5,
),
Container(
height: 50,
width: 270,
decoration: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(20)),
child: HuaweiIdAuthButton(
theme: AuthButtonTheme.FULL_TITLE,
buttonColor: AuthButtonBackground.RED,
borderRadius: AuthButtonRadius.MEDIUM,
onPressed: () {
signInWithHuaweiAccount();
}),
),
SizedBox(
height: 30,
),
GestureDetector(
onTap: () {
showBannerAd();
},
child: Text('New User? Create Account'),
),
],
),
),
),
);
}
void showBannerAd() {
BannerAd _bannerAd;
_bannerAd = createBannerAd();
_bannerAd
..loadAd()
..show(gravity: Gravity.bottom, offset: 5);
}
//Create BannerAd
static BannerAd createBannerAd() {
BannerAd banner = BannerAd(
adSlotId: "testw6vs28auh3",
size: BannerAdSize.sSmart,
adParam: AdParam());
banner.setAdListener = (AdEvent event, {int? errorCode}) {
print("Banner Ad event : $event");
};
return banner;
}
void signInWithHuaweiAccount() async {
AccountAuthParamsHelper helper = new AccountAuthParamsHelper();
helper.setAuthorizationCode();
try {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
Future<AuthAccount> account = AccountAuthService.signIn(helper);
account.then((value) => Fluttertoast.showToast(
msg: "Welcome " + value.displayName.toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0));
Navigator.push(context, MaterialPageRoute(builder: (_) => Main1()));
} 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);
}
BannerAd createAd() {
return BannerAd(
adSlotId: "testw6vs28auh3",
size: BannerAdSize.s468x60,
adParam: AdParam(),
);
}
}
Main.dart
Code:
class Main extends StatefulWidget {
@override
_Main1State createState() => _Main1State();
}
var cardAspectRation = 12.0 / 20.0;
var widgetAspectRatio = cardAspectRation * 1.2;
var verticalInset = 20.0;
class _Main1State extends State<Main1> {
var currentPage = images.length - 1.0;
bool isMenuClosed = true;
late double screenWidth;
final HMSAnalytics _hmsAnalytics = new HMSAnalytics();
@override
void dispose() {
// SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
super.dispose();
}
@override
initState() {
// SystemChrome.setEnabledSystemUIOverlays([]);
super.initState();
_enableLog();
}
Future<void> _enableLog() async {
_hmsAnalytics.setUserId("TestUserStoryApp");
await _hmsAnalytics.enableLog();
}
@override
Widget build(BuildContext context) {
// The initial todos
PageController controller = PageController(initialPage: images.length - 1);
controller.addListener(() {
setState(() {
currentPage = controller.page!;
});
});
Size size = MediaQuery.of(context).size;
screenWidth = size.width;
return Scaffold(
backgroundColor: Colors.grey[850],
body: Stack(
children: <Widget>[
menu(context),
dashboard(context),
],
),
);
}
Widget menu(context) {
return Padding(
padding: EdgeInsets.fromLTRB(0, 0, screenWidth * 0.15, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
flex: 4,
child: Container(
color: Colors.grey[850],
child: Align(
alignment: Alignment.center,
child: circularImage(),
),
),
),
Flexible(
flex: 6,
child: Container(
child: Row(
children: <Widget>[
Flexible(
child: Column(
children: <Widget>[
Flexible(
child: GestureDetector(
onTap: () {
print("Clicked on Ads");
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SecondScreen()));
},
child: Container(
decoration: new BoxDecoration(
color: Color.fromRGBO(218, 107, 107, 1),
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(80.0))),
child: Align(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.headset,
color: Colors.white,
size: 50,
),
Text('Ads',
style: TextStyle(
color: Colors.white, fontSize: 22))
],
),
),
),
),
),
Flexible(
child: GestureDetector(
onTap: () {
print("Clicked on browse");
},
child: Container(
color: Color.fromRGBO(211, 96, 96, 1),
child: Align(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.satellite,
color: Colors.white,
size: 50,
),
Text('Browse',
style: TextStyle(
color: Colors.white, fontSize: 22))
],
),
),
),
),
)
],
),
),
Flexible(
child: Column(
children: <Widget>[
Flexible(
child: GestureDetector(
onTap: () {
print("Clicked on Analytics");
sendCustomEvent();
},
child: Container(
decoration: new BoxDecoration(
color: Color.fromRGBO(211, 96, 96, 1),
borderRadius: new BorderRadius.only(
topRight: const Radius.circular(80.0))),
child: Align(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.assignment,
color: Colors.white,
size: 50,
),
Text('Analytics',
style: TextStyle(
color: Colors.white, fontSize: 22))
],
),
),
),
),
),
Flexible(
child: GestureDetector(
onTap: () {
print("Clicked on settings");
},
child: Container(
color: Color.fromRGBO(218, 107, 107, 1),
child: Align(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.settings,
color: Colors.white,
size: 50,
),
Text('Settings',
style: TextStyle(
color: Colors.white, fontSize: 22))
],
),
),
),
),
)
],
),
)
],
),
),
)
],
),
);
}
Widget dashboard(context) {
return AnimatedPositioned(
//top: isMenuClosed? 0 : 100,
//bottom: isMenuClosed? 0 : 100,
top: 0,
bottom: 0,
left: isMenuClosed ? 0 : screenWidth - screenWidth * 0.15,
right: isMenuClosed ? 0 : -90,
duration: Duration(milliseconds: 300),
child: Material(
elevation: 8,
color: Colors.grey[850],
child: Padding(
padding: EdgeInsets.fromLTRB(10, 30, 10, 10),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
child: Icon(
Icons.segment,
color: Colors.white,
size: 40,
),
onTap: () {
setState(() {
isMenuClosed = !isMenuClosed;
});
},
),
Icon(
Icons.search_outlined,
color: Colors.white,
size: 40,
),
],
),
Text("Trending",
style: TextStyle(fontSize: 28, color: Colors.white)),
CardScrollWidget(currentPage),
],
),
),
),
);
}
Widget circularImage() {
return Container(
width: 200.0,
height: 200.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.teal, width: 10.0, style: BorderStyle.solid),
image: new DecorationImage(
fit: BoxFit.cover, image: AssetImage("images/logo_huawei.png"))),
);
}
void sendCustomEvent() async {
String value = "This is custom event from app";
dynamic eventData = {'Message': value};
await _hmsAnalytics.onEvent("CustomEvent", eventData);
print("Event posted");
}
}
class CardScrollWidget extends StatelessWidget {
var currentPage;
var padding = 20.0;
CardScrollWidget(this.currentPage);
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: widgetAspectRatio,
child: LayoutBuilder(
builder: (context, constraints) {
var width = constraints.maxWidth;
var height = constraints.maxHeight;
var safeWidth = width - 2 * padding;
var safeHeight = height - 2 * padding;
var heightOfPrimaryCard = safeHeight;
var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRation;
var primaryCardLeft = safeWidth - widthOfPrimaryCard;
var horizontalInset = primaryCardLeft / 2;
List<Widget> cardList = [];
for (var i = 0; i < images.length; i++) {
var delta = i - currentPage;
bool isOnRight = delta > 0;
var start = padding +
max(
primaryCardLeft -
horizontalInset * -delta * (isOnRight ? 15 : 1),
0.0);
var cardItem = Positioned.directional(
top: padding + verticalInset * max(-delta, 0.0),
bottom: padding + verticalInset * max(-delta, 0.0),
start: start,
textDirection: TextDirection.rtl,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(3.0, 6.0),
blurRadius: 10.0)
]),
child: AspectRatio(
aspectRatio: cardAspectRation,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset(images[i], fit: BoxFit.cover),
Align(
alignment: Alignment.bottomLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.black45,
borderRadius: BorderRadius.circular(20.0)),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 16.0, vertical: 8.0),
child: Text(title[i],
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
fontFamily: "SF-Pro-Text-Regular")),
),
),
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(
left: 12.0, bottom: 12.0),
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius:
BorderRadius.circular(20.0)),
child: GestureDetector(
onTap: () {
print("FFFFFF");
},
child: Text(
"Read more..",
style: TextStyle(color: Colors.white),
),
),
),
)
],
),
)
],
),
),
),
),
);
cardList.add(cardItem);
}
return Stack(
children: cardList,
);
},
),
);
}
}
Result
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 Account kit, Analytics and Ads kit into Huawei StoryApp for flutter. Once Account kit integrated, users can login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission. Analytics helps you to analyse the user behaviour and Ads kit helps you to monetize the app.
Thank you so much for reading, I hope thiis article helps you to understand the integration of Huawei Account kit, Ads kit and Analytics kit in flutter.
Reference
Ads Kit
Analytics Kit
Ads Kit – Training Video
Analytics Kit – Training Video
Checkout in forum
Related
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Account Kit in Huawei StoryApp. 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.
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.
A Huawei 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.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
JavaScript:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
JavaScript:
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.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA"/>
Step 4: Download flutter plugins
Flutter plugin for Account kit
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.
Let's start coding
loginScreen.dart
Java:
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> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login Page"),
backgroundColor: Colors.grey[850],
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(60.0)),
child: Image.asset('images/logo_huawei.png')),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter valid email id '),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, 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: 250,
decoration: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(20)),
child: FlatButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => Main1()));
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 5,
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.red, borderRadius: BorderRadius.circular(20)),
child: FlatButton(
onPressed: () {
signInWithHuaweiAccount();
},
child: Text(
'Login Huawei ID',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 30,
),
Text('New User? Create Account')
],
),
),
);
}
void signInWithHuaweiAccount() async {
AccountAuthParamsHelper helper = new AccountAuthParamsHelper();
helper.setAuthorizationCode();
try {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
Future<AuthAccount> account = AccountAuthService.signIn(helper);
account.then((value) => Fluttertoast.showToast(
msg: "Welcome " + value.displayName.toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0));
Navigator.push(context, MaterialPageRoute(builder: (_) => Main1()));
} on Exception catch (e) {
print(e.toString());
}
}
}
Main.dart
JavaScript:
class Main1 extends StatefulWidget {
@override
_Main1State createState() => _Main1State();
}
var cardAspectRation = 12.0 / 20.0;
var widgetAspectRatio = cardAspectRation * 1.2;
var verticalInset = 20.0;
class _Main1State extends State<Main1> {
var currentPage = images.length - 1.0;
@override
void dispose() {
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
super.dispose();
}
@override
initState() {
SystemChrome.setEnabledSystemUIOverlays([]);
super.initState();
}
@override
Widget build(BuildContext context) {
PageController controller = PageController(initialPage: images.length - 1);
controller.addListener(() {
setState(() {
currentPage = controller.page!;
});
});
return Scaffold(
backgroundColor: Colors.grey[850],
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 12.0, right: 12.2, top: 10.0, bottom: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
onPressed: () {},
icon: Icon(CustomIcons.menu,
color: Colors.white, size: 30.0),
),
IconButton(
onPressed: () {},
icon: Icon(Icons.search, color: Colors.white, size: 30.0),
)
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Trending",
style: TextStyle(
color: Colors.white,
fontSize: 40.0,
fontFamily: "Calibre-Semibold",
letterSpacing: 1.0),
),
IconButton(
onPressed: () {},
icon: Icon(
CustomIcons.option,
size: 12.0,
color: Colors.white,
))
],
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.deepOrangeAccent,
borderRadius: BorderRadius.circular(20.0),
),
child: Center(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
child: Text(
"Programs",
style: TextStyle(color: Colors.white),
),
),
),
),
SizedBox(
width: 15.0,
),
Text(
"25+ Stories",
style: TextStyle(color: Colors.blueAccent),
)
],
),
),
GestureDetector(
onTap: () {
print("Clicked " + currentPage.toInt().toString());
_launchURL(url[currentPage.toInt()]);
},
child: Stack(
children: <Widget>[
CardScrollWidget(currentPage),
Positioned.fill(
child: PageView.builder(
itemCount: images.length,
controller: controller,
reverse: true,
itemBuilder: (BuildContext context, int index) {
return Container();
},
))
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Favourite",
style: TextStyle(
color: Colors.white,
fontSize: 40.0,
fontFamily: "Calibre-Semibold",
letterSpacing: 1.0),
),
IconButton(
onPressed: () {},
icon: Icon(
CustomIcons.option,
size: 12.0,
color: Colors.white,
))
],
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.deepOrangeAccent,
borderRadius: BorderRadius.circular(20.0),
),
child: Center(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
child: Text(
"Programs",
style: TextStyle(color: Colors.white),
),
),
),
),
SizedBox(
width: 15.0,
),
Text(
"32+ Stories",
style: TextStyle(color: Colors.blueAccent),
)
],
),
)
],
),
));
}
void _launchURL(String url) async {
debugPrint('..... Clicked.....');
if (!await launch(url)) throw 'Could not launch url';
}
}
class CardScrollWidget extends StatelessWidget {
var currentPage;
var padding = 20.0;
CardScrollWidget(this.currentPage);
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: widgetAspectRatio,
child: LayoutBuilder(
builder: (context, constraints) {
var width = constraints.maxWidth;
var height = constraints.maxHeight;
var safeWidth = width - 2 * padding;
var safeHeight = height - 2 * padding;
var heightOfPrimaryCard = safeHeight;
var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRation;
var primaryCardLeft = safeWidth - widthOfPrimaryCard;
var horizontalInset = primaryCardLeft / 2;
List<Widget> cardList = [];
for (var i = 0; i < images.length; i++) {
var delta = i - currentPage;
bool isOnRight = delta > 0;
var start = padding +
max(
primaryCardLeft -
horizontalInset * -delta * (isOnRight ? 15 : 1),
0.0);
var cardItem = Positioned.directional(
top: padding + verticalInset * max(-delta, 0.0),
bottom: padding + verticalInset * max(-delta, 0.0),
start: start,
textDirection: TextDirection.rtl,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(3.0, 6.0),
blurRadius: 10.0)
]),
child: AspectRatio(
aspectRatio: cardAspectRation,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset(images[i], fit: BoxFit.cover),
Align(
alignment: Alignment.bottomLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.black45,
borderRadius: BorderRadius.circular(20.0)),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 16.0, vertical: 8.0),
child: Text(title[i],
style: TextStyle(
color: Colors.white,
fontSize: 25.0,
fontFamily: "SF-Pro-Text-Regular")),
),
),
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(
left: 12.0, bottom: 12.0),
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius:
BorderRadius.circular(20.0)),
child: GestureDetector(
onTap: () {
print("FFFFFF");
},
child: Text(
"Read more..",
style: TextStyle(color: Colors.white),
),
),
),
)
],
),
)
],
),
),
),
),
);
cardList.add(cardItem);
}
return Stack(
children: cardList,
);
},
),
);
}
}
Result
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 Account Kit into Huawei StoryApp for flutter. 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 Huawei Account kit in flutter.
Reference
Account Kit
Checkout in forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Account, Push kit 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 Push kit is a messaging service provided for you. It establishes a messaging channel from the cloud to devices. By integrating Push Kit, you can send messages to your apps on user’s devices in real time. This helps you to maintain closer ties with users and increases user awareness and engagement with your apps.
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.
Previous article
Please check my previous article if you have not gone through, click on link.
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.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
[/B][/B]
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
[B][B]
Root level gradle dependencies
[/B][/B][/B]
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
[B][B][B]
Step 3: Add the below permissions in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Download flutter push kit 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.
Let's start coding
loginScreen.dart
[/B][/B]
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: () {
//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.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,
),
GestureDetector(
onTap: () {
//showBannerAd();
},
child: Text('New User? Create Account'),
),
],
),
),
),
);
}
void signInWithHuaweiID() async {
AccountAuthParamsHelper helper = new AccountAuthParamsHelper();
String name = '';
helper.setAuthorizationCode();
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) => 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);
}
}
[B][B]
main.dart
[/B][/B][/B]
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 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> {
late String gender = '', dietPlan, activeLevel;
late double? age, height, weight, tagetWeight;
TextEditingController ageController = TextEditingController();
TextEditingController heightController = TextEditingController();
TextEditingController weightController = TextEditingController();
TextEditingController targetWeightController = TextEditingController();
late SharedPreferences prefs;
String _genderLabel = "Male";
String _dietLabel = "Veg";
String _activeLable = "Low Active";
final _genderList = ["Male", "Women"];
final _dietPlanList = ["Veg", "Veg-Non Veg", "Egg"];
final _activeLevelList = ["Low Active", "Mid-Active", "Very Active"];
String _token = '';
void initState() {
super.initState();
initPreferences();
initTokenStream();
}
Future<void> initTokenStream() async {
if (!mounted) return;
Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError);
getToken();
}
void getToken() async {
// Call this method to request for a token
Push.getToken("");
}
void _onTokenEvent(String event) {
// Requested tokens can be obtained here
setState(() {
_token = event;
print("TokenEvent: " + _token);
});
}
void _onTokenError(Object error) {
print("TokenErrorEvent: " + error.toString());
PlatformException? e = error as PlatformException?;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title.toString()),
automaticallyImplyLeading: false,
),
body: Center(
child: SingleChildScrollView(
reverse: true,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <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 '),
),
),
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();
gender = value.toString();
});
},
value: _genderLabel,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
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();
dietPlan = value.toString();
print('Diet plan changed to $value');
});
},
value: _dietLabel,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
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(() {
activeLevel = value.toString();
_activeLable = value.toString();
print('Active level changed to $value');
});
},
value: _activeLable,
)
],
)
,
Padding(
padding: const EdgeInsets.only(
left: 22.0, right: 22.0, top: 20, bottom: 0),
child: MaterialButton(
child: const Text(
'Submit',
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.w300),
),
height: 45,
minWidth: 140,
color: Colors.lightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
onPressed: () {
print('Button clicked.....');
age = double.parse(ageController.text);
height = double.parse(heightController.text);
weight = double.parse(weightController.text);
tagetWeight = double.parse(targetWeightController.text);
storeDataLocally();
},
),
),
],
),
),
),
),
);
}
Future<void> storeDataLocally() async {
prefs.setString("name", widget.title.toString());
prefs.setDouble("age", age!);
prefs.setDouble("height", height!);
prefs.setString("gender", gender.toString());
prefs.setDouble("weight", weight!);
prefs.setString("dietPlan", dietPlan);
prefs.setDouble("targetWeight", tagetWeight!);
prefs.setString("activeLevel", activeLevel);
}
Future<void> initPreferences() async {
prefs = await SharedPreferences.getInstance();
showData();
}
void showData() {
if (prefs.getDouble('age').toString() != null) {
ageController.text = prefs.getDouble('age').toString();
heightController.text = prefs.getDouble('height').toString();
targetWeightController.text = prefs.getDouble('targetWeight').toString();
genderController.text = prefs.getString('gender').toString();
dietPlanController.text = prefs.getString('dietPlan').toString();
activeLevelPlanController.text =
prefs.getString('activeLevel').toString();
}
}
}
[B][B][B]
Result
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, Push kit and Analytics 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. Push kit enables you to send push notification to user device in real time, you can see the push notification in the result part.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit, Push kit and Analytics kit in flutter DietApp.
Reference
Push Kit - Training Video
Account Kit – Training Video
Checkout in forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Account, Push kit and Analytics kit in Flutter DietApp. In this article we can see on filling form diet plan i.e. what kind of food you can have to gain/loose the weight with images, we can see in the Diet screen. 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 Push kit is a messaging service provided for you. It establishes a messaging channel from the cloud to devices. By integrating Push Kit, you can send messages to your apps on user’s devices in real time. This helps you to maintain closer ties with users and increases user awareness and engagement with your apps.
Huawei Analytics is a one-stop solution to get user behavior 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.
Previous article
Please check my previous articles if you have not gone through, click on part-2.
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.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
Root level gradle dependencies
Step 3: Add the below permissions in Android Manifest file.
Step 4: Download flutter push kit 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.
Let's start coding
SplashScreen.dart
[/B]
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(
Duration(seconds: 3),
() => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => const LoginScreen())));
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white, child: Image.asset('images/logo_huawei.png'));
}
}
[B]
loginScreen.dart
[/B]
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.blue,
),
body: RefreshIndicator(
onRefresh: showToast,
child: SingleChildScrollView(
child: Column(
children: <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 name = '';
helper.setAuthorizationCode();
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) => 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);
}
}
[B]
main.dart
[/B][/B]
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 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> {
late double? age, height, 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-Active";
final _genderList = ["Male", "Women"];
final _dietPlanList = ["Veg", "Non Veg", "Egg"];
final _activeLevelList = ["Low-Active", "Mid-Active", "Very Active"];
String _token = '';
void initState() {
initPreferences();
initTokenStream();
super.initState();
}
Future<void> initTokenStream() async {
if (!mounted) return;
Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError);
getToken();
}
void getToken() async {
// Call this method to request for a token
Push.getToken("");
}
void _onTokenEvent(String event) {
// Requested tokens can be obtained here
setState(() {
_token = event;
print("TokenEvent: " + _token);
});
}
void _onTokenError(Object error) {
print("TokenErrorEvent: " + error.toString());
PlatformException? e = error as PlatformException?;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title.toString()),
automaticallyImplyLeading: false,
),
body: Center(
child: SingleChildScrollView(
reverse: true,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <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,
children: [
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,
children: [
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.only(
left: 22.0, right: 22.0, top: 20, bottom: 0),
child: MaterialButton(
child: const Text(
'Next',
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.w300),
),
height: 45,
minWidth: 140,
color: Colors.lightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
onPressed: () {
print('Button clicked.....');
age = double.parse(ageController.text);
height = double.parse(heightController.text);
weight = double.parse(weightController.text);
tagetWeight = double.parse(targetWeightController.text);
days = double.parse(inDaysWeightController.text);
storeDataLocally();
},
),
),
],
),
),
),
),
);
}
Future<void> storeDataLocally() async {
prefs.setString("name", widget.title.toString());
prefs.setDouble("age", age!);
prefs.setDouble("height", height!);
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("Diet Plan ===>" + prefs.getString('dietPlan').toString());
print("Active Level ===>" + prefs.getString('activeLevel').toString());
if (prefs.getDouble('age')! > 10) {
ageController.text = prefs.getDouble('age').toString();
heightController.text = prefs.getDouble('height').toString();
targetWeightController.text = prefs.getDouble('targetWeight').toString();
genderController.text = prefs.getString('gender').toString();
dietPlanController.text = prefs.getString('dietPlan').toString();
weightController.text = prefs.getDouble('weight').toString();
inDaysWeightController.text = prefs.getDouble('inDays').toString();
activeLevelPlanController.text =
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();
}
}
}
}
[B][B]
dietPlanScreen.dart
[/B][/B][/B]
class DietPlanScreen extends StatelessWidget {
const DietPlanScreen({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Exercise&DietApp',
home: MyHomePage(
title: 'Diet',
),
);
}
}
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> {
late SharedPreferences prefs;
String dietPlan = '', wt_lg = '';
double wt = 0;
bool isGain = false;
void initState() {
initPreference();
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title.toString()),
backgroundColor: Colors.blue,
automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
child: Card(
color: Colors.white,
child: Center(
child: Padding(
padding: EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Card(
elevation: 3,
shape: Border(
right: BorderSide(color: Colors.red, width: 5)),
child: Padding(
padding: EdgeInsets.all(20),
child: Text(
dietPlan,
style: const TextStyle(
fontSize: 19, color: Colors.deepOrange),
),
),
),
Visibility(
visible: isGain,
child: Card(
elevation: 3,
shape: Border(
right: BorderSide(
color: Colors.greenAccent, width: 5)),
child: Padding(
padding: EdgeInsets.all(5),
child: ExpansionTile(
title: Text('Diet Plan',
style: TextStyle(
fontSize: 22, color: Colors.teal)),
subtitle: Text('To $wt_lg $wt kg weight'),
children: <Widget>[
Text(
'Foods to gain weight quickly',
style: TextStyle(
color: Colors.green, fontSize: 20),
),
ListTile(
title: Column(
children: <Widget>[
ListTile(
title: getTile('Milk'),
),
Image.asset('images/milk.jpg'),
ListTile(
title: getTile('Protein shakes'),
),
Image.asset('images/proteinshake.jpg'),
ListTile(
title: getTile('Rice'),
),
Image.asset('images/rice.jpg'),
ListTile(
title: getTile('Nuts and nut butter'),
),
Image.asset('images/nutsbutter.jpg'),
ListTile(
title: getTile('Whole-grain breads'),
),
Image.asset('images/wholegrain.jpg'),
ListTile(
title: getTile('Eggs, Fats and oils'),
),
Image.asset('images/eggfat.jpeg'),
ListTile(
title: getTile('Dried fruits'),
),
Image.asset('images/dryfruit.jpg'),
],
),
),
],
),
),
),
),
Visibility(
visible: !isGain,
child: Card(
elevation: 3,
shape: Border(
right: BorderSide(color: Colors.black26, width: 5)),
child: Padding(
padding: EdgeInsets.all(5),
child: ExpansionTile(
title: Text('Diet Plan',
style: TextStyle(
fontSize: 22, color: Colors.teal)),
subtitle: Text('To $wt_lg $wt kg weight'),
children: <Widget>[
Text(
'Foods to loose weight quickly',
style: TextStyle(
color: Colors.green, fontSize: 20),
),
ListTile(
title: Column(
children: <Widget>[
ListTile(
title: getTile('Beans'),
),
Image.asset('images/beans.jpg'),
ListTile(
title: getTile('Soup'),
),
Image.asset('images/soup.jpg'),
ListTile(
title: getTile('Dark Chocolate'),
),
Image.asset('images/dark_chocolate.jpg'),
ListTile(
title: getTile('Pureed Vegetables'),
),
Image.asset('images/pureed.jpg'),
ListTile(
title: getTile('Yogurt with berries'),
),
Image.asset('images/yogurt.jpg'),
ListTile(
title: getTile('Nuts, Apples and Yogurt'),
),
Image.asset('images/nutsapple.jpg'),
ListTile(
title: getTile('Grapefruit'),
),
Image.asset('images/grapefruit.jpg'),
],
),
),
],
),
),
),
),
],
),
),
),
),
),
),
);
}
void getPlan() {
double? days = prefs.getDouble('inDays');
double? tagetWeight = prefs.getDouble('targetWeight');
double? weight = prefs.getDouble('weight');
print('Target $tagetWeight');
print('weight $weight');
setState(() {
if (tagetWeight! > weight!) {
setState(() {
isGain = true;
});
wt_lg = 'gain';
wt = tagetWeight - weight;
dietPlan = 'Aim is to $wt_lg $wt kg weight in $days days.';
} else {
setState(() {
isGain = false;
});
wt_lg = 'loose';
wt = weight - tagetWeight;
dietPlan = 'Aim is to $wt_lg $wt kg weight in $days days.';
}
});
}
Future<void> initPreference() async {
prefs = await SharedPreferences.getInstance();
getPlan();
}
RichText getTile(String item) {
return RichText(
text: TextSpan(
text: '• ',
style: TextStyle(
color: Colors.lightBlue,
),
children: <TextSpan>[
TextSpan(text: '$item', style: TextStyle(fontSize: 18)),
],
),
);
}
}
[B][B][B]
Result
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, Push kit and Analytics 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. Push kit enables you to send push notification to user device in real time, you can see the push notification in the result part.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit, Push kit and Analytics kit in flutter DietApp.
Reference
Push Kit
Account Kit – Training Video
Push Kit – Training Video
Checkout in forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Account, Push kit and Analytics kit in Flutter DietApp. Here we can see on filling form diet plan i.e. what kind of food you can have to gain/loose the weight with images, we can see in the diet screen with paid diet plan. 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 Push kit is a messaging service provided for you. It establishes a messaging channel from the cloud to devices. By integrating Push Kit, you can send messages to your apps on user’s devices in real time. This helps you to maintain closer ties with users and increases user awareness and engagement with your apps.
Huawei Analytics is a one-stop solution to get user behavior 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.
We will also learn to integrate Huawei Crash Service in this application. It is a responsibility of the developer to build crash free i.e. unexpected exit of application, it is very difficult to find the cause of the crash in huge application code base. This unexpected crash makes app users annoying and may lead to business loss and reduce market value of the product and the company. To avoid such crashes Huawei provides Crash service which makes developer to find the crash and cause of unexpected exit of the application in AG-console. Crash SDK provides very simple and developer need not code much to implementation crash service. You can also download the detailed crash report whenever required.
Previous article
Please check my previous articles, if you have not gone through, click on part-3.
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.
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 push kit 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.
Lets start coding
SplashScreen.dart
[/B]
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(
Duration(seconds: 3),
() => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => const LoginScreen())));
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white, child: Image.asset('images/logo_huawei.png'));
}
}
[B]
loginScreen.dart
[/B][/B]
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.blue,
),
body: RefreshIndicator(
onRefresh: showToast,
child: SingleChildScrollView(
child: Column(
children: <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 name = '';
helper.setAuthorizationCode();
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) => 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);
}
}
[B][B]
main.dart
[/B][/B][/B]
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 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> {
late double? age, height, 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-Active";
final _genderList = ["Male", "Women"];
final _dietPlanList = ["Veg", "Non Veg", "Egg"];
final _activeLevelList = ["Low-Active", "Mid-Active", "Very Active"];
String _token = '';
void initState() {
initPreferences();
initTokenStream();
super.initState();
}
Future<void> initTokenStream() async {
if (!mounted) return;
Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError);
getToken();
}
void getToken() async {
// Call this method to request for a token
Push.getToken("");
}
void _onTokenEvent(String event) {
// Requested tokens can be obtained here
setState(() {
_token = event;
print("TokenEvent: " + _token);
});
}
void _onTokenError(Object error) {
print("TokenErrorEvent: " + error.toString());
PlatformException? e = error as PlatformException?;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title.toString()),
automaticallyImplyLeading: false,
),
body: Center(
child: SingleChildScrollView(
reverse: true,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <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,
children: [
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,
children: [
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.only(
left: 22.0, right: 22.0, top: 20, bottom: 0),
child: MaterialButton(
child: const Text(
'Next',
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.w300),
),
height: 45,
minWidth: 140,
color: Colors.lightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
onPressed: () {
print('Button clicked.....');
age = double.parse(ageController.text);
height = double.parse(heightController.text);
weight = double.parse(weightController.text);
tagetWeight = double.parse(targetWeightController.text);
days = double.parse(inDaysWeightController.text);
storeDataLocally();
},
),
),
],
),
),
),
),
);
}
Future<void> storeDataLocally() async {
prefs.setString("name", widget.title.toString());
prefs.setDouble("age", age!);
prefs.setDouble("height", height!);
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("Diet Plan ===>" + prefs.getString('dietPlan').toString());
print("Active Level ===>" + prefs.getString('activeLevel').toString());
if (prefs.getDouble('age')! > 10) {
ageController.text = prefs.getDouble('age').toString();
heightController.text = prefs.getDouble('height').toString();
targetWeightController.text = prefs.getDouble('targetWeight').toString();
genderController.text = prefs.getString('gender').toString();
dietPlanController.text = prefs.getString('dietPlan').toString();
weightController.text = prefs.getDouble('weight').toString();
inDaysWeightController.text = prefs.getDouble('inDays').toString();
activeLevelPlanController.text =
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();
}
}
}
}
[B][B][B]
paidPlanScreen.dart
[/B][/B][/B][/B]
class PaidPlanScreen extends StatelessWidget {
String plan = '';
PaidPlanScreen(this.plan, {Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '$plan',
home: MyHomePage(
title: '$plan',
),
);
}
}
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> {
late SharedPreferences prefs;
String dietPlan = '', wt_lg = '';
double wt = 0;
bool isGain = false;
void initState() {
initPreference();
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(widget.title.toString()),
backgroundColor: Colors.blue,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: SingleChildScrollView(
child: Card(
color: Colors.white,
child: Center(
child: Padding(
padding: EdgeInsets.all(15),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Card(
elevation: 3,
shape: Border(
right: BorderSide(color: Colors.red, width: 5)),
child: Padding(
padding: EdgeInsets.all(20),
child: Text(
dietPlan,
style: const TextStyle(
fontSize: 19, color: Colors.deepOrange),
),
),
),
Card(
elevation: 3,
shape: Border(
right:
BorderSide(color: Colors.greenAccent, width: 5)),
child: Padding(
padding: EdgeInsets.all(5),
child: ExpansionTile(
title: Text('Week 1',
style:
TextStyle(fontSize: 22, color: Colors.teal)),
children: <Widget>[
ListTile(
title: getTile('Day 1'),
),
Padding(
padding: EdgeInsets.all(15),
child: Image.asset('images/day1.png'),
),
Text(
'Breakfast: 1 serving Avocado-Egg Toast (271 calories)'
'A.M. Snack: 1 medium orange (62 calories)'
'Lunch: 1 serving Butternut Squash Soup with Avocado & Chickpeas (402 calories)'
'P.M. Snack: 1 medium kiwi (42 calories)'
'Dinner: 1 serving Citrus Poached Salmon with Asparagus with 3/4 cup Cauliflower Rice (451 calories)'
'Daily Totals: 1,228 calories, 58 g protein, 126 g carbohydrates, 30 g fiber, 59 g fat, 1,709 mg sodium.'
'',
style:
TextStyle(color: Colors.green, fontSize: 20),
),
ListTile(
title: Column(
children: <Widget>[
ListTile(
title: getTile('Day 2'),
),
Padding(
padding: EdgeInsets.all(15),
child: Image.asset('images/day2.png'),
),
Text(
'Breakfast: 1 serving Blueberry-Banana Overnight Oats (285 calories)'
'A.M. Snack: 1 serving Apple Cider Vinegar Tonic (22 calories)'
'Lunch: 1 1/2 cups Slow-Cooker Vegetable Soup with 1 slice Everything Bagel Avocado Toast (347 calories)'
'P.M. Snack: 1/2 cup edamame (in pods) sprinkled with a pinch of coarse sea salt (100 calories)'
'Dinner: 1 serving Vegan Coconut Chickpea Curry (471 calories)'
'Meal-Prep Tip: Prepare the Blueberry-Banana Overnight Oats so its ready to grab-and-go in the morning of Day 3.'
'Daily Totals: 1,225 calories, 41 g protein, 181 g carbohydrates, 36 g fiber, 41 g fat, 1,842 mg sodium.',
style: TextStyle(
color: Colors.green, fontSize: 20),
),
/* Image.asset('images/day3.jpg'),
ListTile(
title: getTile('Day 3 '),
),
Image.asset('images/eggfat.jpeg'),
ListTile(
title: getTile('Dried fruits'),
),
Image.asset('images/dryfruit.jpg'),*/
],
),
),
],
),
),
),
Card(
elevation: 3,
shape: Border(
right:
BorderSide(color: Colors.greenAccent, width: 5)),
child: Padding(
padding: EdgeInsets.all(5),
child: ExpansionTile(
title: Text('Week 2',
style:
TextStyle(fontSize: 22, color: Colors.teal)),
children: <Widget>[
ListTile(
title: getTile('Day 1'),
),
Padding(
padding: EdgeInsets.all(15),
child: Image.asset('images/day1.png'),
),
Text(
'Breakfast: 1 serving Avocado-Egg Toast (271 calories)'
'A.M. Snack: 1 medium orange (62 calories)'
'Lunch: 1 serving Butternut Squash Soup with Avocado & Chickpeas (402 calories)'
'P.M. Snack: 1 medium kiwi (42 calories)'
'Dinner: 1 serving Citrus Poached Salmon with Asparagus with 3/4 cup Cauliflower Rice (451 calories)'
'Daily Totals: 1,228 calories, 58 g protein, 126 g carbohydrates, 30 g fiber, 59 g fat, 1,709 mg sodium.'
'',
style:
TextStyle(color: Colors.green, fontSize: 20),
),
ListTile(
title: Column(
children: <Widget>[
ListTile(
title: getTile('Day 2'),
),
Padding(
padding: EdgeInsets.all(15),
child: Image.asset('images/day2.png'),
),
Text(
'Breakfast: 1 serving Blueberry-Banana Overnight Oats (285 calories)'
'A.M. Snack: 1 serving Apple Cider Vinegar Tonic (22 calories)'
'Lunch: 1 1/2 cups Slow-Cooker Vegetable Soup with 1 slice Everything Bagel Avocado Toast (347 calories)'
'P.M. Snack: 1/2 cup edamame (in pods) sprinkled with a pinch of coarse sea salt (100 calories)'
'Dinner: 1 serving Vegan Coconut Chickpea Curry (471 calories)'
'Meal-Prep Tip: Prepare the Blueberry-Banana Overnight Oats so its ready to grab-and-go in the morning of Day 3.'
'Daily Totals: 1,225 calories, 41 g protein, 181 g carbohydrates, 36 g fiber, 41 g fat, 1,842 mg sodium.',
style: TextStyle(
color: Colors.green, fontSize: 20),
),
/* Image.asset('images/day3.jpg'),
ListTile(
title: getTile('Day 3 '),
),
Image.asset('images/eggfat.jpeg'),
ListTile(
title: getTile('Dried fruits'),
),
Image.asset('images/dryfruit.jpg'),*/
],
),
),
],
),
),
),
],
),
),
),
),
),
),
);
}
void getPlan() {
double? days = prefs.getDouble('inDays');
double? tagetWeight = prefs.getDouble('targetWeight');
double? weight = prefs.getDouble('weight');
print('Target $tagetWeight');
print('weight $weight');
setState(() {
if (tagetWeight! > weight!) {
setState(() {
isGain = true;
});
wt_lg = 'gain';
wt = tagetWeight - weight;
dietPlan = 'Aim is to $wt_lg $wt kg weight in $days days.';
} else {
setState(() {
isGain = false;
});
wt_lg = 'loose';
wt = weight - tagetWeight;
dietPlan = 'Aim is to $wt_lg $wt kg weight in $days days.';
}
});
}
Future<void> initPreference() async {
prefs = await SharedPreferences.getInstance();
getPlan();
}
RichText getTile(String item) {
return RichText(
text: TextSpan(
text: '• ',
style: TextStyle(
color: Colors.lightBlue,
),
children: <TextSpan>[
TextSpan(text: '$item', style: TextStyle(fontSize: 18)),
],
),
);
}
}
[B][B][B][B]
How do I report a crash?
[/B][/B][/B][/B]
void crashTest() {
CrashService.enableCollection();
AGCCrash.instance.setUserId("TestDietApp");
AGCCrash.instance.setCustomKey("Test",
"This is test crash for crash service while login button click.");
AGCCrash.instance.setCustomKey("LoginCLickTestCrash", "Crash Test");
AGCCrash.instance.testIt();
}
[B][B][B][B]
Result
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, Push kit and Crash 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. Push kit enables you to send push notification to user device in real time, you can see the push notification in the result part. Huawei Crash service which provides developers to quickly detect, locate and fix the crash or unexpected exit of application. Hence improves stability and reliability of application.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit, Push kit and Crash kit in flutter DietApp.
Reference
Crash Kit
Account Kit – Training Video
Push Kit – Training Video
Crash Kit – Training Video
Checkout in forum
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will be integrating Huawei Remote Configuration service, Account 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.
We will also learn to integrate Huawei Crash Service in this application. It is a responsibility of the developer to build crash free i.e. unexpected exit of application, it is very difficult to find the cause of the crash in huge application code base. This unexpected crash makes app users annoying and may lead to business loss and reduce market value of the product and the company. To avoid such crashes Huawei provides Crash service which makes developer to find the crash and cause of unexpected exit of the application in AG-console.
Crash SDK provides very simple and developer need not code much to implementation crash service. You can also download the detailed crash report whenever required.
Remote Configuration is a service provided by Huawei. It provides cloud-based services. Once you integrate the client SDK, your app can periodically fetch parameter values from the cloud. The service checks whether the parameter that your app tries fetching has an on-cloud value update and returns the new value if so. Based on the parameter values fetched, you can implement service processing logic to change behavior or appearance of your app. In this sample i.e. DietApp, we are fetching the Personal Exercise data using Remote Configuration service by AppGallery.
Previous article
Please check my previous articles, if you have not gone through, click on part-4.
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.
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: Add downloaded file into parent directory of the project. Declare plugin path in pubspec.yaml file under dependencies.
Add path location for asset image.
Let's start coding
SplashScreen.dart
[/B]
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(
Duration(seconds: 3),
() => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => const LoginScreen())));
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white, child: Image.asset('images/logo_huawei.png'));
}
}
[B]
loginScreen.dart
[/B]
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.blue,
),
body: RefreshIndicator(
onRefresh: showToast,
child: SingleChildScrollView(
child: Column(
children: <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 name = '';
helper.setAuthorizationCode();
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) => 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);
}
}
[B]
main.dart
[/B][/B]
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// 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> {
late double? age, height, 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-Active";
final _genderList = ["Male", "Women"];
final _dietPlanList = ["Veg", "Non Veg", "Egg"];
final _activeLevelList = ["Low-Active", "Mid-Active", "Very Active"];
String _token = '';
void initState() {
initPreferences();
initTokenStream();
super.initState();
}
Future<void> initTokenStream() async {
if (!mounted) return;
Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError);
getToken();
}
void getToken() async {
// Call this method to request for a token
Push.getToken("");
}
void _onTokenEvent(String event) {
// Requested tokens can be obtained here
setState(() {
_token = event;
print("TokenEvent: " + _token);
});
}
void _onTokenError(Object error) {
print("TokenErrorEvent: " + error.toString());
PlatformException? e = error as PlatformException?;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text(widget.title.toString()),
automaticallyImplyLeading: false,
),
body: Center(
child: SingleChildScrollView(
reverse: true,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <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,
children: [
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,
children: [
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.only(
left: 22.0, right: 22.0, top: 20, bottom: 0),
child: MaterialButton(
child: const Text(
'Next',
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.w300),
),
height: 45,
minWidth: 140,
color: Colors.lightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
onPressed: () {
print('Button clicked.....');
age = double.parse(ageController.text);
height = double.parse(heightController.text);
weight = double.parse(weightController.text);
tagetWeight = double.parse(targetWeightController.text);
days = double.parse(inDaysWeightController.text);
storeDataLocally();
},
),
),
],
),
),
),
),
);
}
Future<void> storeDataLocally() async {
prefs.setString("name", widget.title.toString());
prefs.setDouble("age", age!);
prefs.setDouble("height", height!);
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("Diet Plan ===>" + prefs.getString('dietPlan').toString());
print("Active Level ===>" + prefs.getString('activeLevel').toString());
if (prefs.getDouble('age')! > 10) {
ageController.text = prefs.getDouble('age').toString();
heightController.text = prefs.getDouble('height').toString();
targetWeightController.text = prefs.getDouble('targetWeight').toString();
genderController.text = prefs.getString('gender').toString();
dietPlanController.text = prefs.getString('dietPlan').toString();
weightController.text = prefs.getDouble('weight').toString();
inDaysWeightController.text = prefs.getDouble('inDays').toString();
activeLevelPlanController.text =
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();
}
}
}
}
[B][B]
tabScreen.dart
[/B][/B][/B]
class TabScreen extends StatefulWidget {
@override
TabScreenPage createState() => TabScreenPage();
}
class TabScreenPage extends State<TabScreen> {
final rnd = math.Random();
List<String> gridItems = [];
@override
void initState() {
// TODO: implement initState
fetchRemoteConfiguration();
super.initState();
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: const Text(
'Diet Plan',
),
centerTitle: true,
backgroundColor: Colors.blue,
elevation: 0,
),
body: Column(
children: <Widget>[
SizedBox(
height: 50,
child: AppBar(
bottom: const TabBar(
tabs: [
Tab(
text: 'Paid Diet Plans',
),
Tab(
text: 'Personal Exercise',
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
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(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 3,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemCount: gridItems.length,
itemBuilder: (BuildContext ctx, index) {
return Center(
child: GestureDetector(
onTap: () {
print(' ' + gridItems[index]);
},
child: Container(
alignment: Alignment.center,
child: Text(gridItems[index],
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold)),
decoration: BoxDecoration(
color: Colors.primaries[Random()
.nextInt(Colors.primaries.length)],
borderRadius: BorderRadius.circular(15)),
),
),
);
}),
),
),
],
),
),
],
),
),
);
}
void routeScreen(String title) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PaidPlanScreen(title)),
);
}
Future<void> fetchRemoteConfiguration() async {
await AGCRemoteConfig.instance
.fetch()
.catchError((error) => print(error.toString()));
await AGCRemoteConfig.instance.applyLastFetched();
Map value = await AGCRemoteConfig.instance.getMergedAll();
final data = jsonDecode(value["categories"].toString());
List<String> gridItem = List<String>.from(data['categories']);
setState(() {
gridItems.addAll(gridItem);
});
}
}
[B][B][B]
Result
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.
Make sure parameter added in agc is json format.
Conclusion
In this article, we have learnt how to integrate Huawei Remote Configuration service, Account kit, Crash kit 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. Push kit enables you to send push notification to user device in real time, you can see the push notification in the result part. Huawei Crash service which provides developers to quickly detect, locate and fix the crash or unexpected exit of application. Hence improves stability and reliability of application. With the help of Remote Configuration service we are fetching the Personal Exercise data from the cloud.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Remote Configuration, Account kit and Crash kit in flutter DietApp.
Reference
Crash Kit
Account Kit – Training Video
Crash Kit – Training Video
Remote Configuration