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.
doctor_app_flutter/lib/widgets/auth/login_form.dart

504 lines
19 KiB
Dart

import 'package:doctor_app_flutter/lookups/hospital_lookup.dart';
import 'package:doctor_app_flutter/screens/auth/verification_methods_screen.dart';
import 'package:doctor_app_flutter/widgets/shared/app_button.dart';
import 'package:doctor_app_flutter/widgets/shared/app_loader_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/user-guid/text_fields/app_text_form_field.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:imei_plugin/imei_plugin.dart';
import 'package:provider/provider.dart';
import '../../config/shared_pref_kay.dart';
import '../../config/size_config.dart';
import '../../models/doctor/user_model.dart';
import '../../core/viewModel/auth_view_model.dart';
import '../../core/viewModel/hospital_view_model.dart';
import '../../routes.dart';
import '../../util/dr_app_shared_pref.dart';
import '../../util/dr_app_toast_msg.dart';
import '../../util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
DrAppSharedPreferances sharedPref = DrAppSharedPreferances();
DrAppToastMsg toastMsg = DrAppToastMsg();
Helpers helpers = Helpers();
class LoginForm extends StatefulWidget with DrAppToastMsg {
LoginForm({this.changeLoadingStata});
final Function changeLoadingStata;
@override
_LoginFormState createState() => _LoginFormState();
}
//TODO recreate the all page and apply the MVVM here
class _LoginFormState extends State<LoginForm> {
final loginFormKey = GlobalKey<FormState>();
var projectIdController = TextEditingController();
String _platformImei = 'Unknown';
String uniqueId = "Unknown";
var projectsList = [];
bool _isInit = true;
FocusNode focusPass = FocusNode();
FocusNode focusProject = FocusNode();
HospitalViewModel projectsProv;
var userInfo = UserModel(
userID: '',
password: '',
projectID: 15,
languageID: 2,
iPAdress: "11.11.11.11",
versionID: 1.2,
channel: 9,
sessionID: "i1UJwCTSqt");
AuthViewModel authProv;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
authProv = Provider.of<AuthViewModel>(context);
projectsProv = Provider.of<HospitalViewModel>(context);
return Form(
key: loginFormKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
width: SizeConfig.realScreenWidth * 0.90,
height: SizeConfig.realScreenHeight * 0.65,
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
buildSizedBox(),
Padding(
child: AppText(
TranslationBase.of(context).enterCredentials,
fontSize: 18,
fontWeight: FontWeight.bold,
),
padding: EdgeInsets.only(top: 10, bottom: 10)),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6.0)),
border: Border.all(
width: 1.0,
color: HexColor("#CCCCCC"),
),
color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 10, top: 10),
child: AppText(
TranslationBase.of(context).enterId,
fontWeight: FontWeight.w800,
fontSize: 14,
)),
AppTextFormField(
labelText: '',
borderColor: Colors.white,
// keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
// decoration: buildInputDecoration(
// context,
// TranslationBase.of(context).enterId,
// 'assets/images/user_id_icon.png'),
validator: (value) {
if (value != null && value.isEmpty) {
return TranslationBase.of(context)
.pleaseEnterYourID;
}
return null;
},
onSaved: (value) {
if (value != null) userInfo.userID = value.trim();
},
onChanged: (value) {
if (value != null) userInfo.userID = value.trim();
},
onFieldSubmitted: (_) {
focusPass.nextFocus();
},
// onEditingComplete: () {},
// autofocus: false,
)
])),
buildSizedBox(),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6.0)),
border: Border.all(
width: 1.0,
color: HexColor("#CCCCCC"),
),
color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 10, top: 10),
child: AppText(
TranslationBase.of(context).enterPassword,
fontWeight: FontWeight.w800,
fontSize: 14,
)),
AppTextFormField(
focusNode: focusPass,
obscureText: true,
borderColor: Colors.white,
textInputAction: TextInputAction.next,
// decoration: buildInputDecoration(
// context,
// TranslationBase.of(context).enterPassword,
// 'assets/images/password_icon.png'),
validator: (value) {
if (value != null && value.isEmpty) {
return TranslationBase.of(context)
.pleaseEnterPassword;
}
return null;
},
onSaved: (value) {
userInfo.password = value;
},
onFieldSubmitted: (_) {
focusPass.nextFocus();
helpers.showCupertinoPicker(context, projectsList,
'facilityName', onSelectProject);
},
onTap: () {
this.getProjects(userInfo.userID);
},
)
])),
buildSizedBox(),
projectsList.length > 0
? Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6.0)),
border: Border.all(
width: 1.0,
color: HexColor("#CCCCCC"),
),
color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 10, top: 10),
child: AppText(
TranslationBase.of(context).selectYourProject,
fontWeight: FontWeight.w600,
)),
AppTextFormField(
focusNode: focusProject,
controller: projectIdController,
borderColor: Colors.white,
suffixIcon: Icons.arrow_drop_down,
onTap: () {
helpers.showCupertinoPicker(
context,
projectsList,
'facilityName',
onSelectProject);
},
// showCursor: false,
// //readOnly: true,
// decoration: buildInputDecoration(
// context,
// TranslationBase.of(context).selectYourProject,
// 'assets/images/password_icon.png'),
validator: (value) {
if (value != null && value.isEmpty) {
return TranslationBase.of(context)
.pleaseEnterYourProject;
}
return null;
})
]))
: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(6.0)),
border: Border.all(
width: 1.0,
color: HexColor("#CCCCCC"),
),
color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 10, top: 10),
child: AppText(
TranslationBase.of(context).selectYourProject,
fontWeight: FontWeight.w800,
fontSize: 14,
)),
AppTextFormField(
readOnly: true, borderColor: Colors.white,
prefix: IconButton(
icon: Icon(Icons.arrow_drop_down),
iconSize: 30,
padding: EdgeInsets.only(bottom: 30),
),
// decoration: buildInputDecoration(
// context,
// TranslationBase.of(context)
// .pleaseEnterYourProject,
// 'assets/images/password_icon.png')
)
])),
]),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Expanded(
child: Button(
title: TranslationBase.of(context).login,
color: HexColor('#D02127'),
onTap: () {
login(context, authProv, widget.changeLoadingStata);
},
)),
],
)
// Row(
// mainAxisAlignment: MainAxisAlignment.end,
// children: <Widget>[
// RaisedButton(
// onPressed: () {
// login(context, authProv, widget.changeLoadingStata);
// },
// textColor: Colors.white,
// elevation: 0.0,
// padding: const EdgeInsets.all(0.0),
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(10),
// side: BorderSide(width: 0.5, color: HexColor('#CCCCCC'))),
// child: Container(
// padding: const EdgeInsets.all(10.0),
// height: 50,
// width: SizeConfig.realScreenWidth * 0.35,
// child: ),
// )
// ],
// ),
],
),
);
}
/*
*@author: Elham Rababah
*@Date:20/4/2020
*@param: context, hint, asset
*@return: InputDecoration
*@desc: decorate input feilds
*/
InputDecoration buildInputDecoration(BuildContext context, hint, asset) {
return InputDecoration(
// prefixIcon: Image.asset(asset),
hintText: hint,
hintStyle: TextStyle(fontSize: 2 * SizeConfig.textMultiplier),
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(
//borderRadius: BorderRadius.all(Radius.circular(20)),
borderSide: BorderSide(color: HexColor('#CCCCCC')),
),
focusedBorder: OutlineInputBorder(
// borderRadius: BorderRadius.all(Radius.circular(10.0)),
borderSide: BorderSide(color: Theme.of(context).primaryColor),
),
errorBorder: OutlineInputBorder(
// borderRadius: BorderRadius.all(Radius.circular(10.0)),
borderSide: BorderSide(color: Theme.of(context).errorColor),
),
focusedErrorBorder: OutlineInputBorder(
// borderRadius: BorderRadius.all(Radius.circular(10.0)),
borderSide: BorderSide(color: Theme.of(context).errorColor),
),
);
}
SizedBox buildSizedBox() {
return SizedBox(
height: 20,
);
}
login(context, AuthViewModel authProv, Function changeLoadingStata) {
showLoading();
if (loginFormKey.currentState.validate()) {
loginFormKey.currentState.save();
sharedPref.setInt(PROJECT_ID, userInfo.projectID);
authProv.login(userInfo).then((res) {
//changeLoadingStata(false);
hideLoading();
if (res['MessageStatus'] == 1) {
// insertDeviceImei(res, authProv);
saveObjToString(LOGGED_IN_USER, res);
sharedPref.remove(LAST_LOGIN_USER);
sharedPref.setString(TOKEN, res['LogInTokenID']);
print("token" + res['LogInTokenID']);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => VerificationMethodsScreen(
password: userInfo.password,
)));
} else {
// handel error
helpers.showErrorToast(res['ErrorEndUserMessage']);
}
}).catchError((err) {
//TODO change the logic here
if(!err.contains('eservices.hmg@drsulaimanalhabib.com') ){
hideLoading();
changeLoadingStata(false);
helpers.showErrorToast(err);}
});
} else {
changeLoadingStata(false);
}
}
insertDeviceImei(preRes, AuthViewModel authProv) {
if (_platformImei != 'Unknown') {
var imeiInfo = {
"IMEI": _platformImei,
"LogInType": 1,
"DoctorID": preRes['DoctorID'],
"DoctorName": "Test User",
"Gender": 1,
"ClinicID": 3,
"ProjectID": 15,
"DoctorTitle": "Mr.",
"ClinicName": "MED",
"ProjectName": "",
"DoctorImageURL": "UNKNOWN",
"LogInTokenID": preRes['LogInTokenID'],
"VersionID": 5.3
};
authProv.insertDeviceImei(imeiInfo).then((res) {
if (res['MessageStatus'] == 1) {
setSharedPref('platformImei', _platformImei);
saveObjToString(LOGGED_IN_USER, preRes);
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => VerificationMethodsScreen(
password: userInfo.password,
)));
// save imei on shared preferance
} else {
// handel error
helpers.showErrorToast(res['ErrorEndUserMessage']);
}
}).catchError((err) {
print(err);
helpers.showErrorToast();
});
}
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformImei;
String idunique;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformImei =
await ImeiPlugin.getImei(shouldShowRequestPermissionRationale: false);
idunique = await ImeiPlugin.getImei();
} catch (e) {
platformImei = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformImei = platformImei;
uniqueId = idunique;
});
}
Future<void> setSharedPref(key, value) async {
sharedPref.setString(key, value).then((success) {
print("sharedPref.setString" + success.toString());
});
}
getProjectsList(memberID) {
//showLoading();
projectsProv.getProjectsList(memberID).then((res) {
//hideLoading();
if (res['MessageStatus'] == 1) {
projectsList = res['ProjectInfo'];
setState(() {
userInfo.projectID = projectsList[0]["facilityId"];
projectIdController.text = projectsList[0]['facilityName'];
});
} else {
print(res);
// handel error
// setState(() {
// projectsList = ListProject;
// });
}
}).catchError((err) {
setState(() {
print(err);
});
print(err);
});
}
saveObjToString(String key, value) async {
sharedPref.setObj(key, value);
}
onSelectProject(index) {
setState(() {
userInfo.projectID = projectsList[index]["facilityId"];
projectIdController.text = projectsList[index]['facilityName'];
});
primaryFocus.unfocus();
}
showLoading() {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(
child: CircularProgressIndicator(),
);
});
}
hideLoading() {
Navigator.pop(context);
}
getProjects(value) {
if (value != null && value != '') {
if (projectsList.length == 0) {
getProjectsList(value);
}
}
//_isInit = false;
}
}