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

393 lines
13 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_loader_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();
}
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: Container(
width: SizeConfig.realScreenWidth * 0.90,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
buildSizedBox(),
TextFormField(
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
decoration: buildInputDecoration(
context,
TranslationBase.of(context).enterId,
'assets/images/user_id_icon.png'),
validator: (value) {
if (value.isEmpty) {
return TranslationBase.of(context).pleaseEnterYourID;
}
return null;
},
onSaved: (value) {
userInfo.userID = value.trim();
},
onChanged: (value) {
userInfo.userID = value.trim();
},
onFieldSubmitted: (_) {
focusPass.nextFocus();
},
onEditingComplete: () {},
autofocus: false,
),
buildSizedBox(),
TextFormField(
focusNode: focusPass,
obscureText: true,
textInputAction: TextInputAction.next,
decoration: buildInputDecoration(
context,
TranslationBase.of(context).enterPassword,
'assets/images/password_icon.png'),
validator: (value) {
if (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
? TextFormField(
focusNode: focusProject,
controller: projectIdController,
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.isEmpty) {
return TranslationBase.of(context)
.pleaseEnterYourProject;
}
return null;
})
: TextFormField(
readOnly: true,
decoration: buildInputDecoration(
context,
TranslationBase.of(context).pleaseEnterYourProject,
'assets/images/password_icon.png')),
buildSizedBox(),
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: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(TranslationBase.of(context).login,
style: TextStyle(
fontSize: SizeConfig.isMobilePortrait
? 2.3 * SizeConfig.textMultiplier
: 2.3 * SizeConfig.textMultiplier)),
Image.asset('assets/images/login_btn_arrow_icon.png')
],
),
),
)
],
),
],
),
),
);
}
/*
*@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),
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) {
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;
}
}