You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tangheem/lib/ui/common_appbar.dart

544 lines
24 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/api/tangheem_user_api_client.dart';
import 'package:tangheem/api/user_api_client.dart';
import 'package:tangheem/app_state/app_state.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/consts.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/extensions/widget_extensions.dart';
import 'package:tangheem/models/authentication_user_model.dart';
import 'package:tangheem/models/content_info_model.dart';
import 'package:tangheem/models/navigation_model.dart';
import 'package:tangheem/models/quick_links_model.dart';
import 'package:tangheem/ui/dialogs/change_password_dialog.dart';
import 'package:tangheem/ui/dialogs/general_dialog.dart';
import 'package:tangheem/ui/screens/bookmark_screen.dart';
import 'package:tangheem/ui/screens/content_info_screen.dart';
import 'package:tangheem/ui/screens/home_screen.dart';
import 'package:tangheem/ui/screens/login_screen.dart';
import 'package:tangheem/ui/screens/pdf_viewer_screen.dart';
import 'package:url_launcher/url_launcher.dart';
class CommonAppbar extends StatefulWidget {
final bool showDrawer;
final Widget child;
final bool isFirst;
CommonAppbar({Key key, this.showDrawer = false, @required this.child, this.isFirst = false}) : super(key: key);
@override
_CommonAppbarState createState() {
return _CommonAppbarState();
}
}
class _CommonAppbarState extends State<CommonAppbar> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
List<QuickLinksData> quickLinks = [];
List<NavigationDataModel> navigationList = [];
ContentInfoDataModel _userCopyRight;
@override
void initState() {
super.initState();
getPrefs();
getNavigation();
getQuickLinks();
getCopyRight();
}
void getCopyRight() async {
if (AppState().getCopyRightContentInfoModel == null) {
try {
ContentInfoModel _userCopyRight = await TangheemUserApiClient().getContentInfo(3);
this._userCopyRight = _userCopyRight.data.first;
AppState().setCopyRightContentInfoModel(this._userCopyRight);
} catch (ex) {}
} else {
_userCopyRight = AppState().getCopyRightContentInfoModel;
}
setState(() {});
}
void getNavigation() async {
if (AppState().getNavigationModel?.data == null) {
try {
var model = await TangheemUserApiClient().getNavigation();
navigationList = model?.data ?? [];
navigationList.removeWhere((element) => element.navigationId == 9); // this is for temporary, to release app on app store as file size are about 100 mbs
navigationList.sort((a, b) => a.orderNo.compareTo(b.orderNo));
AppState().setNavigationModel(model);
} catch (ex) {}
} else {
navigationList = AppState().getNavigationModel.data;
}
setState(() {});
}
void getQuickLinks() async {
if (widget.showDrawer) {
try {
quickLinks = (await TangheemUserApiClient().quickLinks())?.data ?? [];
quickLinks = quickLinks.where((element) => element.position == "down").toList();
quickLinks.sort((a, b) => a.orderNo.compareTo(b.orderNo));
} catch (ex) {}
setState(() {});
}
}
int fontSize;
SharedPreferences prefs;
void getPrefs() async {
prefs = await SharedPreferences.getInstance();
fontSize = prefs.getInt(GlobalConsts.fontZoomSize) ?? 18;
String userAuth = prefs.getString(GlobalConsts.userAuthData);
if (userAuth != null) {
AuthenticationUserModel authenticationUserModel = AuthenticationUserModel.fromJson(jsonDecode(userAuth));
AppState().setAuthenticationModel(authenticationUserModel);
}
}
void deleteUserAccount() async {
Utils.showLoading(context);
try {
await UserApiClient().deleteAccount(AppState().userId);
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove(GlobalConsts.userAuthData);
AppState().setAuthenticationModel(null);
Utils.showToast("تم حذف الحساب");
Navigator.pop(context);
Utils.hideLoading(context);
} catch (ex) {
if (mounted) {
Utils.hideLoading(context);
Utils.handleException(ex, null);
}
}
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
// key: widget.showDrawer ? _scaffoldKey : null,
// drawer: widget.showDrawer ? drawerView() : null,
// resizeToAvoidBottomInset: true,
// drawerScrimColor: Colors.black.withOpacity(.3),
backgroundColor: ColorConsts.greyF4Color,
body: SizedBox(
width: double.infinity,
child: Stack(
alignment: Alignment.topRight,
children: [
// Container(
// color: Colors.white,
// height: 100,
// padding: EdgeInsets.only(top: 8, bottom: 8, right: 16),
// child: Row(
// crossAxisAlignment: CrossAxisAlignment.center,
// children: [
// if (!widget.isFirst)
// IconButton(
// icon: Icon(widget.showDrawer ? Icons.menu : Icons.arrow_back_ios, color: ColorConsts.textGrey),
// padding: EdgeInsets.only(left: 16),
// onPressed: () {
// if (widget.showDrawer) {
// _scaffoldKey.currentState.openDrawer();
// } else {
// Navigator.pop(context);
// }
// },
// ),
// if (!widget.showDrawer)
// IconButton(
// icon: Icon(Icons.home, color: ColorConsts.textGrey),
// padding: EdgeInsets.only(left: 16),
// onPressed: () {
// Navigator.popUntil(context, ModalRoute.withName(HomeScreen.routeName));
// },
// ),
// Expanded(child: SizedBox()),
// Hero(
// tag: "logo",
// child: SvgPicture.asset(
// "assets/logos/tangheem_logo.svg",
// height: 100,
// width: 100,
// alignment: Alignment.centerRight,
// ),
// )
// ],
// ),
// ),
Directionality(textDirection: TextDirection.rtl, child: widget.child),
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: Icon(
Icons.arrow_forward_ios,
color: ColorConsts.darkText,
).paddingOnly(left: 4),
style: ElevatedButton.styleFrom(
backgroundColor: Color(0xfff4f4f4),
shape: CircleBorder(), //<-- SEE HERE
padding: EdgeInsets.all(8),
),
).paddingOnly(right: 8, top: 50),
// IconButton(
// highlightColor: Colors.green,
// icon: Icon(Icons.arrow_back_ios, color: ColorConsts.textGrey),
// padding: EdgeInsets.only(left: 16),
// onPressed: () {
// Navigator.pop(context);
// },
// ),
],
),
),
);
}
void updatePassword(String email, String oldPassword, String password) async {
Utils.showLoading(context);
try {
await UserApiClient().updatePassword(email, oldPassword, password);
} catch (ex) {
if (mounted) Utils.handleException(ex, null);
Utils.hideLoading(context);
return;
} finally {
Utils.hideLoading(context);
}
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove(GlobalConsts.userAuthData);
AppState().setAuthenticationModel(null);
await showDialog(
context: context,
barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
builder: (BuildContext context) => GeneralDialog(message: "تم تغيير كلمة المرور بنجاح , الرجاء إعادة تسجيل الدخول من خلال الرابط المرسل إلى بريدك الإلكتروني"),
);
Navigator.pop(context);
}
Widget drawerView() {
var height = MediaQuery.of(context).padding.top;
return Drawer(
elevation: 0,
child: Container(
color: Colors.white,
child: SafeArea(
bottom: true,
top: false,
right: false,
left: false,
maintainBottomViewPadding: true,
child: Builder(
builder: (context) {
bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
Widget listContents = ListView.builder(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
padding: EdgeInsets.only(left: 24, right: 24),
itemCount: navigationList.length,
itemBuilder: (context, index) {
String icon = "assets/icons/${navigationList[index].mobileFontIcon}.svg";
var subList = navigationList.where((element) => element.parentId == navigationList[index].navigationId).toList();
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (navigationList[index].parentId == 1)
myListItem(icon, navigationList[index].navigationText, navigationList[index].orderNo == 1 ? true : false, onTap: () {
String url = navigationList[index]?.mobileNavigationUrl ?? "";
if (url.isEmpty || url.length < 2) {
return;
}
Navigator.pushNamed(context, url, arguments: null);
}),
for (var subItem in subList)
Container(
width: double.infinity,
child: Row(
children: [
Expanded(
child: myListItem("assets/icons/${subItem.mobileFontIcon}.svg", subItem.navigationText, false, onTap: () {
String url = subItem.mobileNavigationUrl ?? "";
if (url.isEmpty) {
return;
}
var contentId;
if (subItem.mobileNavigationUrl == "/introduction") {
url = ContentInfoScreen.routeName;
contentId = 2;
} else if (subItem.mobileNavigationUrl == "/encyclopedia") {
url = ContentInfoScreen.routeName;
contentId = 1;
} else if (subItem.mobileNavigationUrl == "/tangheempdf") {
url = PdfListScreen.routeName;
contentId = 8;
}
Navigator.pushNamed(context, url, arguments: contentId);
}),
),
Container(
height: 40,
margin: EdgeInsets.only(right: 17, left: 10),
child: VerticalDivider(color: ColorConsts.primaryBlack, thickness: .7, width: 1),
),
],
),
)
],
);
});
if (isPortrait) {
listContents = Expanded(child: listContents);
}
List<Widget> list = [
Container(
height: 100 + height,
padding: EdgeInsets.only(left: 0, top: height),
alignment: Alignment.centerLeft,
child: IconButton(
icon: Icon(Icons.clear, color: ColorConsts.textGrey),
onPressed: () {
if (_scaffoldKey.currentState.isDrawerOpen) {
Navigator.pop(context);
}
},
),
),
Container(
margin: EdgeInsets.only(top: 8, bottom: 16),
padding: EdgeInsets.only(left: 16, right: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
commonIconButton("assets/icons/bookmark.svg", () {
Navigator.pushNamed(context, BookmarkScreen.routeName);
}),
commonIconButton("assets/icons/increase_size.svg", () {
if (fontSize >= 36) {
Utils.showToast("وصل حجم الخط إلى الحد الأقصى للحجم");
return;
}
fontSize += 2;
prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
Utils.showToast("زيادة حجم الخط");
}),
commonIconButton("assets/icons/reduce_size.svg", () {
if (fontSize <= 12) {
Utils.showToast("وصل حجم الخط إلى الحد الأدنى للحجم");
return;
}
fontSize -= 2;
prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
Utils.showToast("تم تقليل حجم الخط");
}),
commonIconButton("assets/icons/user_logged.svg", () {
if (AppState().isUserLogin) {
Utils.showToast("أنت بالفعل تسجيل الدخول");
return;
}
Navigator.pushNamed(context, LoginScreen.routeName);
}),
if (AppState().isUserLogin)
Expanded(
child: PopupMenuButton(
padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
onSelected: (int index) async {
if (index == 0) {
Navigator.pop(context);
Future.delayed(Duration(milliseconds: 200), () {
showDialog(
context: context,
barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
builder: (BuildContext context) => ChangePasswordDialog(
onPassword: (oldPassword, password) => updatePassword(AppState().userEmail, oldPassword, password),
),
);
});
} else if (index == 1) {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove(GlobalConsts.userAuthData);
AppState().setAuthenticationModel(null);
Utils.showToast("تسجيل خروج المستخدم");
Navigator.pop(context);
} else {
await showDialog(
context: context,
barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
builder: (BuildContext context) => GeneralDialog(
message: 'بحذف حسابك ، ستتم إزالة بياناتك ولن تتمكن من استرداد حسابك. \ n انقر فوق "نعم" لحذف حسابك.',
onTap: () {
Navigator.pop(context);
deleteUserAccount();
},
showCancelButton: true,
),
);
}
},
icon: SvgPicture.asset("assets/icons/fa_key.svg", height: 25, width: 30, color: ColorConsts.textGrey1),
itemBuilder: (_) => <PopupMenuItem<int>>[
PopupMenuItem(
value: 0,
padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
height: 36,
child: Center(
child: Text(
'تغيير كلمة المرور',
style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 16),
),
),
),
PopupMenuItem(
value: 1,
padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
height: 36,
child: Center(
child: Text(
'تسجيل خروج',
style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 16),
),
),
),
PopupMenuItem(
value: 2,
padding: EdgeInsets.fromLTRB(4, 0, 4, 0),
height: 36,
child: Center(
child: Text(
'حذف الحساب',
style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 16),
),
),
),
]),
),
],
),
),
listContents,
Container(
margin: EdgeInsets.only(top: 16, bottom: 12),
padding: EdgeInsets.only(left: 32, right: 32),
child: Row(
children: [
for (QuickLinksData _quickLink in quickLinks)
commonIconButton(ApiConsts.baseUrl + _quickLink.exposeFilePath, () {
//for live production server
// commonIconButton( _quickLink.exposeFilePath, () {
_launchURL(_quickLink.imageUrl);
}, size: 35, isAsset: false),
],
),
),
Padding(
padding: EdgeInsets.only(left: 32, right: 32, bottom: 8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_userCopyRight != null) ...[
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_userCopyRight.content,
maxLines: 1,
textAlign: TextAlign.right,
style: TextStyle(fontSize: 12, color: Colors.black87),
),
SizedBox(width: 8),
Image.network(ApiConsts.baseUrl + _userCopyRight.exposeFilePath, height: 25, width: 30)
],
),
SizedBox(height: 8),
],
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Powered by Cloud Solutions",
maxLines: 1,
textAlign: TextAlign.right,
style: TextStyle(fontSize: 14, color: Colors.black87),
),
SizedBox(width: 8),
SvgPicture.asset("assets/logos/cloud_logo.svg", width: 30, height: 30)
],
),
],
),
)
];
return isPortrait ? Column(children: list) : ListView(children: list);
},
),
),
),
);
}
void _launchURL(String _url) async => await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url';
Widget commonIconButton(String icon, VoidCallback onPressed, {double size, bool isAsset = true}) {
return Expanded(
child: IconButton(
padding: EdgeInsets.zero,
icon: isAsset ? SvgPicture.asset(icon, height: size ?? 25, width: size ?? 30) : Image.network(icon, height: size ?? 25, width: size ?? 30),
onPressed: () {
Navigator.pop(context);
Future.delayed(Duration(milliseconds: 200), () => onPressed());
}),
);
}
Widget myListItem(String icon, String title, bool isSelected, {VoidCallback onTap}) {
return InkWell(
onTap: () {
Navigator.pop(context);
if (onTap != null) {
Future.delayed(Duration(milliseconds: 200), () => onTap());
}
},
child: Container(
height: 40,
padding: EdgeInsets.only(left: 8, right: 8),
alignment: Alignment.centerRight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
gradient: isSelected
? LinearGradient(
stops: [0.0, 0.5],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [ColorConsts.gradientPink, ColorConsts.gradientOrange],
)
: null,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: TextStyle(fontSize: 14, color: isSelected ? Colors.white : ColorConsts.textGrey),
),
SizedBox(width: 8),
SvgPicture.asset(icon, height: 20, width: 20, color: isSelected ? Colors.white : ColorConsts.textGrey),
],
),
),
);
}
}