· 4 years ago · Mar 16, 2021, 09:54 AM
1import 'dart:async';
2import 'dart:convert';
3import 'package:flutter/services.dart';
4import 'package:http/http.dart' as http;
5import 'package:flutter/cupertino.dart';
6import "package:flutter/material.dart";
7import 'package:dkmqa/pages/homepage/homepage.dart';
8import 'package:dkmqa/pages/header/login_appbar.dart';
9
10import 'package:dkmqa/constants/global_variables/global_var.dart';
11import 'package:dkmqa/constants/api/base_api.dart';
12import 'package:dkmqa/constants/messages/messages.dart';
13import 'package:shared_preferences/shared_preferences.dart';
14import 'package:dkmqa/models/login/login_model.dart';
15
16import 'package:dkmqa/constants/messages/error_message.dart';
17
18/// Here is where you specify the style , data or information for log in page, you can specify here the connection for api login
19/// latest edited by: Gian Carlo Garcia / 2020-02-20
20
21String _error_msg = "";
22
23/// SUBMIT BUTTON ///
24// login button function and design is here
25class FormSubmitButton extends StatelessWidget {
26 final Function() onPressed;
27 FormSubmitButton({this.onPressed});
28
29 @override
30 Widget build(BuildContext context) {
31 return SizedBox(
32 child: RaisedButton(
33 onPressed: onPressed,
34 child: Text(event_label, style: TextStyle(color: Colors.white)),
35 shape:
36 RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
37 color: Colors.blue,
38 ),
39 width: double.infinity);
40 }
41}
42
43/// HOMEPAGE ROUTE
44// Responsible for passing to homepage
45class HomepageRoute extends StatelessWidget {
46 @override
47 Widget build(BuildContext context) {
48 return Homepage();
49 }
50}
51
52/// LOGIN PAGE ///
53// responsible for handling all the functions and
54// forms for login page
55class LoginPage extends StatefulWidget {
56 @override
57 _LoginPageState createState() => _LoginPageState();
58}
59
60class _LoginPageState extends State<LoginPage> {
61 // dynamic Messages;
62
63 // uniquely identifies a Form
64 // observe that we're passing the FormState
65 // and not MyFormState which is our widget
66 // holds the form data for access
67 final model = LoginModel();
68 final _formkey = GlobalKey<FormState>();
69 // email RegExp
70 // we'll use this RegExp to check if the
71 // form's emailAddress value entered is a valid
72 // emailAddress or not and raise a validation error
73 // for the erroneous case
74 final _emailRegExp = RegExp(
75 r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
76
77 // TextEditingController _controller_username = new TextEditingController()..text = '@woodmark.com';
78 TextEditingController _controller_username = new TextEditingController();
79 TextEditingController _controller_key1 = new TextEditingController();
80 TextEditingController _controller_key2 = new TextEditingController();
81 TextEditingController _controller_key3 = new TextEditingController();
82 TextEditingController _controller_key4 = new TextEditingController();
83
84 /// WILL CLEAR THE FORM FIELDS ///
85 void clearText() {
86 // _controller_username.clear();
87 _controller_key1.clear();
88 _controller_key2.clear();
89 _controller_key3.clear();
90 _controller_key4.clear();
91 }
92
93 /// This will get the stored sharedpreferences from login
94 error_message() async {
95 SharedPreferences _prefs = await SharedPreferences.getInstance();
96 setState(() {
97 _error_msg = _prefs.getString('_error_msg');
98 print(_error_msg);
99 });
100 }
101
102 resetError() async {
103 SharedPreferences error_prefs = await SharedPreferences.getInstance();
104 error_prefs.remove('_error_msg');
105 bool CheckValue = error_prefs.containsKey('_error_msg');
106 print(CheckValue);
107 print("Error Message cleared");
108 }
109
110 /// API CONNECTION FOR LOGGING IN ///
111 // Responsible for sending the username and password
112 // value in json format to the api
113 final api_url = BaseUrl.baseURL + "user/"; //url or endpoints for api login
114 Future<http.Response> authenticate(String username, String key1, String key2,
115 String key3, String key4) async {
116 var params = "?username=" +
117 username +
118 "&passkey=" +
119 key1 +
120 key2 +
121 key3 +
122 key4 +
123 '&usertype=1&appname=Login';
124 print(key1 + key2 + key3 + key4);
125 final response = await http.get(api_url + params
126
127 // headers: {
128 // 'Content-Type' : 'application/json; charset=UTF-8',
129 // 'Accept' : 'application/json'
130 // },
131 // body: jsonEncode(<String, String>{
132 // 'username' : username,
133 // 'passkey' : password,
134 // }
135 // ),
136 );
137 var data = jsonDecode(response.body);
138
139 dynamic error_msg = "Invalid User ID or Passkey";
140
141 /// RESPONSIBLE FOR CHECKING THE STATUS OF RESPONSE ///
142 // If response was successful, it will redirect to the homepage
143 // it will throw an error message if it's not
144 if (data[0][0] == 1) {
145 // if (username == "inspector@woodmark.com" && password == '0322' ){
146
147 /// SharedPreferences used to get the selected data and store in local to
148 /// use to another page
149 SharedPreferences _prefs = await SharedPreferences.getInstance();
150 _prefs.setString('_plant', model.plant);
151 _prefs.setString('_business', model.business);
152 var event_label = 'Homepage';
153 resetError();
154
155 Navigator.push(
156 context,
157 MaterialPageRoute(builder: (context) => HomepageRoute()),
158 );
159 } else {
160 // If response was unsuccessfull, it will throw an error message
161 error_message();
162 SharedPreferences prefs = await SharedPreferences.getInstance();
163 prefs.setString("_error_msg", error_msg);
164 print(_error_msg);
165 print(error_msg);
166 }
167 }
168
169 bool _checkbox = false;
170
171 /// API for Fetching Language from API ///
172
173 String languageList;
174 List lang = List();
175
176 Future getLanguage() async {
177 var response = await http.get(BaseUrl.baseURL + "api/language/",
178 headers: {"Accept": "application/json"});
179
180 var jsonBody = response.body;
181 var jsonData = jsonDecode(jsonBody);
182
183 setState(() {
184 lang = jsonData;
185 });
186
187 print(jsonData);
188 return "Success";
189 }
190
191 /// ---------------------------- ///
192
193 /// API for Fetching Plant from API ///
194
195 String plantList;
196 List plant_lst = List();
197
198 Future getPlant() async {
199 var response = await http.get(BaseUrl.baseURL + "api/plant/?CorpID=1000",
200 headers: {"Accept": "application/json"});
201
202 var jsonBody = response.body;
203 var jsonData = jsonDecode(jsonBody);
204
205 setState(() {
206 plant_lst = jsonData;
207 });
208
209 print(jsonData);
210 return "Success";
211 }
212
213 /// ---------------------------- ///
214
215 /// API for Fetching Business Line from API ///
216
217 String businessList;
218 List business_line_list = List();
219
220 Future getBusinessLine() async {
221 var response = await http.get(
222 BaseUrl.baseURL + "api/business-line/?CorpID=1000",
223 headers: {"Accept": "application/json"});
224
225 var jsonBody = response.body;
226 var jsonData = jsonDecode(jsonBody);
227
228 setState(() {
229 business_line_list = jsonData;
230 });
231
232 print(jsonData);
233 return "Success";
234 }
235
236 /// ---------------------------- ///
237
238 /// API for Fetching Messages from API ///
239
240 int messageLst;
241 List msgLst = List();
242 dynamic langCode = '101';
243 Future getMessage() async {
244 var response = await http.get(
245 BaseUrl.baseURL +
246 "api/messages/?CorpID=1000&PlantID=100&LangID=" +
247 langCode,
248 headers: {"Accept": "application/json"});
249
250 var jsonBody = response.body;
251 var jsonData = jsonDecode(jsonBody);
252
253 setState(() {
254 language_label = jsonData[48]['LangMsg'];
255 plant_label = jsonData[68]['LangMsg'];
256 email_label = jsonData[30]['LangMsg'];
257 event_label = jsonData[53]['LangMsg'];
258 business_label = jsonData[3]['LangMsg'];
259 passkey_label = jsonData[65]['LangMsg'];
260 version_no = jsonData[112]['LangMsg'];
261 info_int = jsonData[44]['LangMsg'];
262 // plant_error = jsonData[69]['LangMsg'];
263 });
264
265 return "Success";
266 }
267
268 /// ---------------------------- ///
269
270 @override
271 void initState() {
272 super.initState();
273 getLanguage();
274 getPlant();
275 getBusinessLine();
276 // getMessageList();
277 // LoginMessage()
278 getMessage();
279 }
280
281 // messageList() {
282 // final messages = getMessageList();
283 // setState(() {
284 // // language_label = messages.jsonData[];
285 // // plant_label = messages[68]['LangMsg'];
286 // // email_label = messages[30]['LangMsg'];
287 // // event_label = messages[53]['LangMsg'];
288 // // business_label = messages[3]['LangMsg'];
289 // // passkey_label = messages[65]['LangMsg'];
290 // // version_no = messages[112]['LangMsg'];
291 // // info_int = messages[44]['LangMsg'];
292 // // plant_error = messages[69]['LangMsg'];
293 // });
294 // }
295
296 @override
297 Widget build(BuildContext context) {
298 return Scaffold(
299 appBar: CustomAppBar(),
300 body: Center(
301 child: Column(
302 children: [
303 Container(
304 margin: EdgeInsets.fromLTRB(0, 100, 0, 0),
305 width: 600,
306 height: 500,
307 child: Form(
308 key: _formkey,
309 child: Column(
310 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
311 children: <Widget>[
312 Row(
313 children: <Widget>[
314 Container(
315 width: 170.0,
316 child: Text(
317 language_label,
318 style: TextStyle(
319 fontFamily: font_family, fontSize: font_size),
320 ),
321 ),
322 Container(
323 width: 400,
324 margin: EdgeInsets.fromLTRB(25, 0, 0, 0),
325 child: DropdownButtonFormField(
326 decoration: InputDecoration(
327 border: new OutlineInputBorder(
328 borderRadius: new BorderRadius.circular(1.0),
329 borderSide: new BorderSide(),
330 ),
331 ),
332 value: languageList,
333 hint: Text('English'),
334 items: lang.map(
335 (list) {
336 return DropdownMenuItem(
337 child: Text(list['Language']),
338 value: list['LangID'].toString(),
339 );
340 },
341 ).toList(),
342 onChanged: (value) {
343 setState(() {
344 langCode = value;
345 getMessage();
346 });
347 },
348 onSaved: (value) {
349 model.language = value;
350 },
351 ),
352 ),
353 ],
354 ),
355 Row(
356 children: <Widget>[
357 Container(
358 width: 65.0,
359 child: Text(
360 plant_label,
361 style: TextStyle(
362 fontFamily: font_family, fontSize: font_size),
363 ),
364 ),
365 Container(
366 width: 400,
367 margin: EdgeInsets.fromLTRB(130, 25, 0, 0),
368 child: DropdownButtonFormField(
369 decoration: InputDecoration(
370 border: new OutlineInputBorder(
371 borderRadius:
372 new BorderRadius.circular(1.0),
373 borderSide: new BorderSide(),
374 ),
375 ),
376 value: plantList,
377 autovalidateMode:
378 AutovalidateMode.onUserInteraction,
379 validator: (value) =>
380 value == null ? plant_error : null,
381 hint: Text(plant_label),
382 items: plant_lst.map(
383 (list) {
384 return DropdownMenuItem(
385 child: Text(list['PlantName']),
386 value: list['PlantName'],
387 );
388 },
389 ).toList(),
390 onChanged: (value) {
391 setState(() {
392 plantList = value;
393 });
394 },
395 onSaved: (value) {
396 model.plant = value;
397 },
398 ))
399 ],
400 ),
401 Row(
402 children: <Widget>[
403 Container(
404 width: 130.0,
405 child: Text(
406 business_label,
407 style: TextStyle(
408 fontFamily: font_family, fontSize: font_size),
409 ),
410 ),
411 Container(
412 width: 400,
413 margin: EdgeInsets.fromLTRB(65, 25, 0, 0),
414 child: DropdownButtonFormField(
415 decoration: InputDecoration(
416 border: new OutlineInputBorder(
417 borderRadius:
418 new BorderRadius.circular(1.0),
419 borderSide: new BorderSide(),
420 ),
421 ),
422 value: businessList,
423 autovalidateMode:
424 AutovalidateMode.onUserInteraction,
425 validator: (value) =>
426 value == null ? busline_error : null,
427 hint: Text(business_label),
428 items: business_line_list.map(
429 (list) {
430 return DropdownMenuItem(
431 child: Text(list['BusName']),
432 value: list['BusName'],
433 );
434 },
435 ).toList(),
436 onChanged: (value) {
437 setState(() {
438 businessList = value;
439 });
440 },
441 onSaved: (value) {
442 model.business = value;
443 },
444 ))
445 ],
446 ),
447 Row(
448 children: <Widget>[
449 Container(
450 width: 70.0,
451 child: Container(
452 width: 70.0,
453 margin: EdgeInsets.fromLTRB(0, 25, 0, 0),
454 child: Text(
455 email_label,
456 style: TextStyle(
457 fontFamily: font_family,
458 fontSize: font_size),
459 ),
460 ),
461 ),
462 Container(
463 width: 400,
464 margin: EdgeInsets.fromLTRB(125, 25, 0, 0),
465 child: TextFormField(
466 controller: _controller_username,
467 obscureText: false,
468 decoration: InputDecoration(
469 labelText: email_label,
470 border: new OutlineInputBorder(
471 borderRadius: new BorderRadius.circular(1.0),
472 borderSide: new BorderSide(),
473 ),
474 ),
475 autovalidateMode:
476 AutovalidateMode.onUserInteraction,
477 validator: (value) {
478 if (value.isEmpty) {
479 return email_error;
480 } else if (!_emailRegExp.hasMatch(value)) {
481 return 'Invalid email address';
482 }
483 return null;
484 },
485 onSaved: (value) {
486 model.emailAddress = value;
487 },
488 ),
489 ),
490 ],
491 ),
492 Row(
493 children: <Widget>[
494 Container(
495 margin: EdgeInsets.fromLTRB(0, 25, 0, 0),
496 child: Container(
497 width: 86.0,
498 child: Text(
499 passkey_label,
500 style: TextStyle(
501 fontFamily: font_family,
502 fontSize: font_size),
503 ),
504 ),
505 ),
506 Container(
507 width: 50,
508 margin: EdgeInsets.fromLTRB(110, 25, 0, 0),
509 child: TextFormField(
510 textInputAction: TextInputAction.next,
511 onChanged: (_) =>
512 FocusScope.of(context).nextFocus(),
513 controller: _controller_key1,
514 textAlign: TextAlign.center,
515 maxLength: 1,
516 keyboardType: TextInputType.number,
517 inputFormatters: <TextInputFormatter>[
518 FilteringTextInputFormatter.digitsOnly
519 ],
520 obscureText: true,
521 decoration: InputDecoration(
522 border: new OutlineInputBorder(
523 borderRadius:
524 new BorderRadius.circular(1.0),
525 borderSide: new BorderSide(),
526 ),
527 counterText: "",
528 ),
529 autovalidateMode:
530 AutovalidateMode.onUserInteraction,
531 validator: (value) {
532 if (value.isEmpty) {
533 return passkey_error;
534 }
535 return null;
536 },
537 onSaved: (value) {
538 model.key1 = value;
539 }),
540 ),
541 Container(
542 width: 50,
543 margin: EdgeInsets.fromLTRB(10, 25, 0, 0),
544 child: TextFormField(
545 textInputAction: TextInputAction.next,
546 onChanged: (_) =>
547 FocusScope.of(context).nextFocus(),
548 textAlign: TextAlign.center,
549 maxLength: 1,
550 keyboardType: TextInputType.number,
551 inputFormatters: <TextInputFormatter>[
552 FilteringTextInputFormatter.digitsOnly
553 ],
554 controller: _controller_key2,
555 obscureText: true,
556 decoration: InputDecoration(
557 border: new OutlineInputBorder(
558 borderRadius:
559 new BorderRadius.circular(1.0),
560 borderSide: new BorderSide(),
561 ),
562 counterText: "",
563 ),
564 autovalidateMode:
565 AutovalidateMode.onUserInteraction,
566 validator: (value) {
567 if (value.isEmpty) {
568 return passkey_error;
569 }
570 return null;
571 },
572 onSaved: (value) {
573 model.key2 = value;
574 }),
575 ),
576 Container(
577 width: 50,
578 margin: EdgeInsets.fromLTRB(10, 25, 0, 0),
579 child: TextFormField(
580 textInputAction: TextInputAction.next,
581 onChanged: (_) =>
582 FocusScope.of(context).nextFocus(),
583 textAlign: TextAlign.center,
584 maxLength: 1,
585 keyboardType: TextInputType.number,
586 inputFormatters: <TextInputFormatter>[
587 FilteringTextInputFormatter.digitsOnly
588 ],
589 controller: _controller_key3,
590 obscureText: true,
591 decoration: InputDecoration(
592 border: new OutlineInputBorder(
593 borderRadius:
594 new BorderRadius.circular(1.0),
595 borderSide: new BorderSide(),
596 ),
597 counterText: "",
598 ),
599 autovalidateMode:
600 AutovalidateMode.onUserInteraction,
601 validator: (value) {
602 if (value.isEmpty) {
603 var message = passkey_error;
604 }
605 return null;
606 },
607 onSaved: (value) {
608 model.key3 = value;
609 }),
610 ),
611 Container(
612 width: 50,
613 margin: EdgeInsets.fromLTRB(10, 25, 0, 0),
614 child: TextFormField(
615 textInputAction: TextInputAction.next,
616 onChanged: (_) =>
617 FocusScope.of(context).nextFocus(),
618 textAlign: TextAlign.center,
619 maxLength: 1,
620 keyboardType: TextInputType.number,
621 inputFormatters: <TextInputFormatter>[
622 FilteringTextInputFormatter.digitsOnly
623 ],
624 controller: _controller_key4,
625 obscureText: true,
626 decoration: InputDecoration(
627 border: new OutlineInputBorder(
628 borderRadius:
629 new BorderRadius.circular(1.0),
630 borderSide: new BorderSide(),
631 ),
632 counterText: "",
633 ),
634 autovalidateMode:
635 AutovalidateMode.onUserInteraction,
636 validator: (value) {
637 if (value.isEmpty) {
638 return passkey_error;
639 }
640 return null;
641 },
642 onSaved: (value) {
643 model.key4 = value;
644 }),
645 ),
646 Container(
647 width: 140,
648 height: 50,
649 margin: EdgeInsets.fromLTRB(25, 12, 0, 0),
650 child: FormSubmitButton(onPressed: () {
651 if (_formkey.currentState.validate()) {
652 _formkey.currentState.save();
653 clearText();
654 var _username = model.emailAddress;
655 var key1 = model.key1;
656 var key2 = model.key2;
657 var key3 = model.key3;
658 var key4 = model.key4;
659 var language = model.language;
660 var plant = model.plant;
661 var business = model.business;
662 print(language);
663 print(plant);
664 print(business);
665
666 authenticate(_username, key1, key2, key3, key4);
667 // the model object at this point can be POSTed
668 // to an API or persisted for further use
669
670 // Scaffold.of(
671 // _formkey.currentContext)
672 // .showSnackBar(
673 // SnackBar(content: Text(
674 // 'Processing Data')));
675 }
676 }),
677 ),
678 ],
679 ),
680 // Expanded(
681 // child: Row(
682 // children: <Widget>[
683 // Container(
684 // margin: EdgeInsets.fromLTRB(0, 25, 0, 0),
685 // child: Row(
686 // children: [
687 // Checkbox(
688 // value: _checkbox,
689 // onChanged: (value) {
690 // setState(() {
691 // _checkbox = !_checkbox;
692 // });
693 // },
694 // ),
695 // Text(
696 // "Set as default",
697 // style: TextStyle(
698 // fontFamily: font_family,
699 // fontSize: font_size),
700 // ),
701 // ],
702 // ),
703 // ),
704 // ],
705 // ),
706 // ),
707 ],
708 ),
709 )),
710 // Expanded(
711 // child: Row(
712 // children: [
713 // Container(
714 // margin: EdgeInsets.fromLTRB(530, 300, 0,0),
715 // child: RaisedButton(
716 // onPressed: () {},
717 // child:
718 // Text(
719 // "Continue/Next",
720 // style: TextStyle(
721 // color: Colors.white,
722 // fontSize: font_size,
723 // fontFamily: font_family
724 // ),
725 // ),
726 // color: Colors.blue[400],
727 // ),
728 // ),
729 // ],
730 // ),
731 // )
732 ],
733 ),
734 ),
735 bottomNavigationBar: BottomAppBar(
736 child: CustomLoginFooter(),
737 ),
738 );
739 }
740}
741
742class CustomLoginFooter extends PreferredSize {
743 @override
744
745 /// size of footer height
746 Size get preferredSize => Size.fromHeight(115);
747
748 @override
749 Widget build(BuildContext context) {
750 // TODO: implement build
751 return Container(
752 height: preferredSize.height,
753 child: Column(
754 children: [
755 Row(
756 children: <Widget>[
757 Expanded(
758 ////////////////// Information and Instruction //////////////////
759 child: Container(
760 padding: EdgeInsets.all(10),
761 child: Text(
762 info_int,
763 textAlign: TextAlign.center,
764 style:
765 TextStyle(fontSize: font_size, fontFamily: font_family),
766 ),
767 color: Colors.blue[400],
768 ),
769 ),
770 ],
771 ),
772 Row(
773 children: <Widget>[
774 Expanded(
775 ////////////////// Error Message //////////////////
776 child: Container(
777 padding: EdgeInsets.all(10),
778 child: Text(
779 errorMessage().toString(),
780 textAlign: TextAlign.center,
781 style:
782 TextStyle(fontSize: font_size, fontFamily: font_family),
783 ),
784 color: error_color,
785 ),
786 ),
787 ],
788 ),
789 Row(
790 children: <Widget>[
791 Expanded(
792 ////////////////// Version No. //////////////////
793 child: Container(
794 padding: EdgeInsets.all(10),
795 child: Text(
796 version_no,
797 textAlign: TextAlign.center,
798 style:
799 TextStyle(fontSize: font_size, fontFamily: font_family),
800 ),
801 color: Colors.green,
802 ),
803 ),
804 Expanded(
805 ////////////////// App Name //////////////////
806 child: Container(
807 padding: EdgeInsets.all(10),
808 child: Text(
809 app_name,
810 textAlign: TextAlign.center,
811 style:
812 TextStyle(fontSize: font_size, fontFamily: font_family),
813 ),
814 color: Colors.green,
815 ),
816 ),
817 Expanded(
818 ////////////////// Device Id //////////////////
819 child: Container(
820 padding: EdgeInsets.all(10),
821 child: Text(
822 device,
823 textAlign: TextAlign.center,
824 style:
825 TextStyle(fontSize: font_size, fontFamily: font_family),
826 ),
827 color: Colors.green,
828 ),
829 ),
830 Expanded(
831 ////////////////// Device Id //////////////////
832 child: Container(
833 padding: EdgeInsets.all(10),
834 child: Text(
835 role,
836 textAlign: TextAlign.center,
837 style:
838 TextStyle(fontSize: font_size, fontFamily: font_family),
839 ),
840 color: Colors.green,
841 ),
842 ),
843 ],
844 ),
845 ],
846 ),
847 );
848 }
849}
850