Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 23.20 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:io';
  3.  
  4. import 'package:dio/dio.dart';
  5. import 'package:flushbar/flushbar.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  9. import 'package:i_manual/appLocalizations.dart';
  10. import 'package:i_manual/customDio.dart';
  11. import 'package:image_picker/image_picker.dart';
  12.  
  13. const LISTTOPPADDING = 30 / 812;
  14. const LISTDETAILTOPPADDING = 20 / 812;
  15.  
  16. const HORIZONTALPADDINGDETAILEDITEM = 10 / 375;
  17. const LEFTTITLESPADDING = 34 / 375;
  18.  
  19. const ITEMWIDTH = 300.0;
  20.  
  21. const PROBLEMSBOTTOMPADDING = 11 / 812;
  22. const PROBLEMLEFTPADDING = 40 / 375;
  23. const BUTTONHORIZONTALPADDING = 20 / 375;
  24. const BUTTONBOTTOMPADDING = 20 / 812;
  25.  
  26. const MODALICONBOTTOMPADDING = 40 / 812;
  27. const MODALBUTTOMTOPPADDING = 40 / 812;
  28. const MODALBUTTONHORIZONTALPADDING = 25 / 375;
  29.  
  30. class Register extends StatefulWidget {
  31.   @override
  32.   _RegisterState createState() => _RegisterState();
  33. }
  34.  
  35. class _RegisterState extends State<Register> {
  36.   File _image;
  37.   TextEditingController _firstNameController;
  38.   TextEditingController _lastNameController;
  39.   TextEditingController _emailController;
  40.   TextEditingController _passwordController;
  41.   FocusNode _passwordFocusNode;
  42.   FocusNode _lastNameFocusNode;
  43.   FocusNode _emailFocusNode;
  44.   FocusNode _birdthDayFocusNode;
  45.   FocusNode _genderFocusNode;
  46.   DateTime birdthDayValue;
  47.   String genderValue;
  48.   String englishGenderValue;
  49.   bool submitting = false;
  50.  
  51.   bool createdAccount = false;
  52.  
  53.   @override
  54.   void initState() {
  55.     super.initState();
  56.     _firstNameController = TextEditingController(text: '');
  57.     _lastNameController = TextEditingController(text: '');
  58.     _emailController = TextEditingController(text: '');
  59.     _passwordController = TextEditingController(text: '');
  60.     _passwordFocusNode = FocusNode();
  61.     _lastNameFocusNode = FocusNode();
  62.     _emailFocusNode = FocusNode();
  63.     _birdthDayFocusNode = FocusNode();
  64.     _genderFocusNode = FocusNode();
  65.   }
  66.  
  67.   Future getImage() async {
  68.     var image = await ImagePicker.pickImage(source: ImageSource.camera);
  69.     setState(() {
  70.       _image = image;
  71.     });
  72.   }
  73.  
  74.   genderActionSheetMethod(BuildContext context) {
  75.     final AppLocalizations localization = AppLocalizations.of(context);
  76.  
  77.     final List _genderOptions = [
  78.       {"locale": localization.male, "english": "male"},
  79.       {"locale": localization.female, "english": "female"},
  80.       {"locale": localization.noGender, "english": "pnts"}
  81.     ];
  82.  
  83.     showCupertinoModalPopup(
  84.         context: context,
  85.         builder: (context) {
  86.           return Container(
  87.             height: MediaQuery.of(context).size.height / 5,
  88.             child: CupertinoPicker(
  89.               onSelectedItemChanged: (item) {
  90.                 setState(() {
  91.                   genderValue = _genderOptions[item]["locale"];
  92.                   englishGenderValue = _genderOptions[item]["english"];
  93.                 });
  94.               },
  95.               itemExtent: 32.0,
  96.               children: _genderOptions
  97.                   .map((gender) => Text(gender["locale"]))
  98.                   .toList(),
  99.             ),
  100.           );
  101.         });
  102.   }
  103.  
  104.   birthDateTapHandler(BuildContext context) {
  105.     showCupertinoModalPopup(
  106.         context: context,
  107.         builder: (context) {
  108.           return Container(
  109.             height: MediaQuery.of(context).size.height / 5,
  110.             child: CupertinoDatePicker(
  111.                 mode: CupertinoDatePickerMode.date,
  112.                 onDateTimeChanged: (DateTime date) {
  113.                   setState(() {
  114.                     birdthDayValue = date;
  115.                   });
  116.                 }),
  117.           );
  118.         });
  119.   }
  120.  
  121.   handleCreate(Size deviceSize) async {
  122.     final AppLocalizations localization = AppLocalizations.of(context);
  123.     setState(() {
  124.       submitting = true;
  125.     });
  126.     try {
  127.       final dio = await CustomDio.getInstance();
  128.  
  129.       await dio.post("users", data: {
  130.         "first_name": _firstNameController.text,
  131.         "last_name": _lastNameController.text,
  132.         "gender": englishGenderValue,
  133.         "email": _emailController.text,
  134.         "username": _emailController.text,
  135.         "password": _passwordController.text,
  136.         "birthdate": birdthDayValue.toIso8601String()
  137.       });
  138.  
  139.       final loginResponse = await dio
  140.           .post("http://manual-252420.appspot.com/auth/login", data: {
  141.         "username": _emailController.text,
  142.         "password": _passwordController.text
  143.       });
  144.  
  145.       final storage = FlutterSecureStorage();
  146.       await storage.write(
  147.           key: "accessToken", value: loginResponse.data["access_token"]);
  148.       await storage.write(
  149.           key: "refreshToken", value: loginResponse.data["refresh_token"]);
  150.       final firstTimeOpen = await storage.read(key: "firstTimeOpen");
  151.  
  152.       setState(() {
  153.         createdAccount = true;
  154.         submitting = false;
  155.       });
  156.  
  157.       Flushbar(
  158.         title: "Success",
  159.         message: localization.userCreateSuccessMessage,
  160.         icon: Icon(
  161.           Icons.check,
  162.           color: CupertinoColors.white,
  163.         ),
  164.         duration: Duration(seconds: 3),
  165.         onStatusChanged: (FlushbarStatus status) async {
  166.           if (status == FlushbarStatus.DISMISSED) {
  167.             if (firstTimeOpen == null)
  168.               await Navigator.pushNamedAndRemoveUntil(
  169.                   context, "/tutorial", (Route<dynamic> route) => false);
  170.             else
  171.               await Navigator.pushNamedAndRemoveUntil(
  172.                   context, "/myHomePage", (Route<dynamic> route) => false);
  173.           }
  174.         },
  175.         backgroundColor: Colors.green,
  176.         flushbarStyle: FlushbarStyle.GROUNDED,
  177.       )..show(context);
  178.     } on DioError catch (e) {
  179.       String errorMessage = '';
  180.  
  181.       setState(() {
  182.         submitting = false;
  183.       });
  184.  
  185.       if (e.response != null) {
  186.         if (e.response.statusCode == 422) {
  187.           if (e.response.data.runtimeType == String)
  188.             errorMessage = e.response.data;
  189.           else
  190.             e.response.data.forEach((key, errors) {
  191.               final withoutDotsErrorMessage =
  192.                   errors.map((error) => error.replaceAll(".", "")).toList();
  193.               final errorField = key.toString();
  194.  
  195.               errorMessage = errorMessage +
  196.                   "${errorField[0].toUpperCase()}${errorField.substring(1)}: ${withoutDotsErrorMessage.join(", ")}";
  197.             });
  198.         } else
  199.           errorMessage = localization.unexpectedError;
  200.       } else {
  201.         errorMessage = localization.networkError;
  202.       }
  203.       Flushbar(
  204.         title: localization.unexpectedError,
  205.         message: errorMessage,
  206.         icon: Icon(
  207.           Icons.error_outline,
  208.           color: CupertinoColors.white,
  209.         ),
  210.         duration: Duration(seconds: 3),
  211.         backgroundColor: Color(0xFFf44336),
  212.         flushbarStyle: FlushbarStyle.GROUNDED,
  213.       )..show(context);
  214.     } catch (e) {
  215.       setState(() {
  216.         submitting = false;
  217.       });
  218.  
  219.       Flushbar(
  220.         title: localization.unexpectedError,
  221.         message: localization.unexpectedError,
  222.         icon: Icon(
  223.           Icons.error_outline,
  224.           color: CupertinoColors.white,
  225.         ),
  226.         duration: Duration(seconds: 3),
  227.         backgroundColor: Color(0xFFf44336),
  228.         flushbarStyle: FlushbarStyle.GROUNDED,
  229.       )..show(context);
  230.     }
  231.   }
  232.  
  233.   @override
  234.   Widget build(BuildContext context) {
  235.     final deviceSize = MediaQuery.of(context).size;
  236.     final AppLocalizations localization = AppLocalizations.of(context);
  237.     final disabledSubmit = _firstNameController.text.isEmpty ||
  238.         _lastNameController.text.isEmpty ||
  239.         birdthDayValue == null ||
  240.         genderValue == null ||
  241.         _emailController.text.isEmpty ||
  242.         _passwordController.text.isEmpty ||
  243.         createdAccount;
  244.  
  245.     return CupertinoPageScaffold(
  246.       navigationBar: CupertinoNavigationBar(
  247.         middle: Text(localization.register,
  248.             style: TextStyle(
  249.               fontWeight: FontWeight.w300,
  250.               fontFamily:
  251.                   CupertinoTheme.of(context).textTheme.textStyle.fontFamily,
  252.               fontSize: 22,
  253.               color: CupertinoColors.white,
  254.             )),
  255.         backgroundColor: Color(0xFF5F688B),
  256.       ),
  257.       child: GestureDetector(
  258.         onTap: () {
  259.           FocusScope.of(context).requestFocus(new FocusNode());
  260.         },
  261.         child: SafeArea(child: Container(
  262.           child: LayoutBuilder(builder: (context, constraints) {
  263.             return Material(
  264.               color: CupertinoTheme.of(context).scaffoldBackgroundColor,
  265.               child: Padding(
  266.                 padding: EdgeInsets.symmetric(
  267.                     horizontal: constraints.maxWidth * BUTTONHORIZONTALPADDING),
  268.                 child: ListView(
  269.                   children: <Widget>[
  270.                     Padding(
  271.                       padding: EdgeInsets.only(
  272.                         top: deviceSize.height * LISTTOPPADDING,
  273.                       ),
  274.                       child: Row(
  275.                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
  276.                         children: <Widget>[
  277.                           Flexible(
  278.                             flex: 30,
  279.                             child: Text(
  280.                               localization.firstName,
  281.                               style: TextStyle(fontSize: 17),
  282.                             ),
  283.                           ),
  284.                           Flexible(
  285.                             flex: 70,
  286.                             child: CupertinoTextField(
  287.                               controller: _firstNameController,
  288.                               style: TextStyle(fontSize: 16),
  289.                               onSubmitted: (value) {
  290.                                 FocusScope.of(context)
  291.                                     .requestFocus(_lastNameFocusNode);
  292.                               },
  293.                               keyboardType: TextInputType.text,
  294.                               textCapitalization: TextCapitalization.words,
  295.                               textInputAction: TextInputAction.next,
  296.                             ),
  297.                           ),
  298.                         ],
  299.                       ),
  300.                     ),
  301.                     Padding(
  302.                       padding: EdgeInsets.only(
  303.                         top: deviceSize.height * LISTTOPPADDING,
  304.                       ),
  305.                       child: Row(
  306.                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
  307.                         children: <Widget>[
  308.                           Flexible(
  309.                             flex: 30,
  310.                             child: Text(
  311.                               localization.lastName,
  312.                               style: TextStyle(fontSize: 17),
  313.                             ),
  314.                           ),
  315.                           Flexible(
  316.                             flex: 70,
  317.                             child: CupertinoTextField(
  318.                               controller: _lastNameController,
  319.                               focusNode: _lastNameFocusNode,
  320.                               style: TextStyle(fontSize: 16),
  321.                               keyboardType: TextInputType.text,
  322.                               textInputAction: TextInputAction.next,
  323.                               textCapitalization: TextCapitalization.words,
  324.                               onSubmitted: (value) {
  325.                                 FocusScope.of(context)
  326.                                     .requestFocus(_birdthDayFocusNode);
  327.                               },
  328.                             ),
  329.                           ),
  330.                         ],
  331.                       ),
  332.                     ),
  333.                     Padding(
  334.                       padding: EdgeInsets.only(
  335.                         top: deviceSize.height * LISTTOPPADDING,
  336.                       ),
  337.                       child: Row(
  338.                         mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  339.                         children: <Widget>[
  340.                           Flexible(
  341.                             fit: FlexFit.tight,
  342.                             flex: 30,
  343.                             child: Text(
  344.                               localization.birthDate,
  345.                               style: TextStyle(fontSize: 17),
  346.                             ),
  347.                           ),
  348.                           Flexible(
  349.                               fit: FlexFit.tight,
  350.                               flex: 70,
  351.                               child: Focus(
  352.                                 focusNode: _birdthDayFocusNode,
  353.                                 onFocusChange: (focused) {
  354.                                   if (focused) birthDateTapHandler(context);
  355.                                 },
  356.                                 child: Padding(
  357.                                   padding:
  358.                                       const EdgeInsets.symmetric(vertical: 8.0),
  359.                                   child: GestureDetector(
  360.                                     onTap: () {
  361.                                       birthDateTapHandler(context);
  362.                                     },
  363.                                     child: Text(
  364.                                       birdthDayValue == null
  365.                                           ? localization.tapToSelect
  366.                                           : "${birdthDayValue.year}-${birdthDayValue.month}-${birdthDayValue.day}",
  367.                                       textAlign: TextAlign.center,
  368.                                       style: TextStyle(fontSize: 16),
  369.                                     ),
  370.                                   ),
  371.                                 ),
  372.                               )),
  373.                         ],
  374.                       ),
  375.                     ),
  376.                     Padding(
  377.                       padding: EdgeInsets.only(
  378.                         top: deviceSize.height * LISTTOPPADDING,
  379.                       ),
  380.                       child: Row(
  381.                         mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  382.                         children: <Widget>[
  383.                           Flexible(
  384.                             fit: FlexFit.tight,
  385.                             flex: 30,
  386.                             child: Text(
  387.                               localization.gender,
  388.                               style: TextStyle(fontSize: 17),
  389.                             ),
  390.                           ),
  391.                           Flexible(
  392.                               fit: FlexFit.tight,
  393.                               flex: 70,
  394.                               child: Focus(
  395.                                 focusNode: _genderFocusNode,
  396.                                 child: Padding(
  397.                                   padding:
  398.                                       const EdgeInsets.symmetric(vertical: 8.0),
  399.                                   child: GestureDetector(
  400.                                     onTap: () {
  401.                                       genderActionSheetMethod(context);
  402.                                     },
  403.                                     child: Text(
  404.                                       genderValue == null
  405.                                           ? localization.tapToSelect
  406.                                           : genderValue,
  407.                                       textAlign: TextAlign.center,
  408.                                       style: TextStyle(fontSize: 16),
  409.                                     ),
  410.                                   ),
  411.                                 ),
  412.                               )),
  413.                         ],
  414.                       ),
  415.                     ),
  416.                     Padding(
  417.                       padding: EdgeInsets.only(
  418.                         top: deviceSize.height * LISTTOPPADDING,
  419.                       ),
  420.                       child: Row(
  421.                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
  422.                         children: <Widget>[
  423.                           Flexible(
  424.                             flex: 30,
  425.                             child: Text(
  426.                               localization.email,
  427.                               style: TextStyle(fontSize: 17),
  428.                             ),
  429.                           ),
  430.                           Flexible(
  431.                             flex: 70,
  432.                             child: CupertinoTextField(
  433.                               controller: _emailController,
  434.                               style: TextStyle(fontSize: 16),
  435.                               onSubmitted: (value) {
  436.                                 FocusScope.of(context)
  437.                                     .requestFocus(_passwordFocusNode);
  438.                               },
  439.                               textInputAction: TextInputAction.next,
  440.                               keyboardType: TextInputType.emailAddress,
  441.                             ),
  442.                           ),
  443.                         ],
  444.                       ),
  445.                     ),
  446.                     Padding(
  447.                       padding: EdgeInsets.only(
  448.                         top: deviceSize.height * LISTTOPPADDING,
  449.                       ),
  450.                       child: Row(
  451.                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
  452.                         children: <Widget>[
  453.                           Flexible(
  454.                             flex: 30,
  455.                             child: Text(
  456.                               localization.password,
  457.                               style: TextStyle(fontSize: 17),
  458.                             ),
  459.                           ),
  460.                           Flexible(
  461.                             flex: 70,
  462.                             child: CupertinoTextField(
  463.                               controller: _passwordController,
  464.                               focusNode: _passwordFocusNode,
  465.                               style: TextStyle(fontSize: 16),
  466.                               obscureText: true,
  467.                               keyboardType: TextInputType.emailAddress,
  468.                             ),
  469.                           ),
  470.                         ],
  471.                       ),
  472.                     ),
  473. //                  Padding(
  474. //                    padding: EdgeInsets.only(
  475. //                      left: deviceSize.width * LEFTTITLESPADDING,
  476. //                      top: deviceSize.height * LISTTOPPADDING,
  477. //                      bottom: deviceSize.height * LISTDETAILTOPPADDING,
  478. //                    ),
  479. //                    child: Row(
  480. //                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  481. //                      children: <Widget>[
  482. //                        Flexible(
  483. //                          fit: FlexFit.tight,
  484. //                          flex: 30,
  485. //                          child: Text(
  486. //                            localization.image,
  487. //                            style: TextStyle(
  488. //                              fontSize: 17,
  489. //                            ),
  490. //                          ),
  491. //                        ),
  492. //                        Flexible(
  493. //                            fit: FlexFit.tight,
  494. //                            flex: 70,
  495. //                            child: Container(
  496. //                              child: Row(
  497. //                                children: <Widget>[
  498. //                                  GestureDetector(
  499. //                                    onTap: getImage,
  500. //                                    child: Container(
  501. //                                      height: 100,
  502. //                                      width: 100,
  503. //                                      decoration: BoxDecoration(
  504. //                                          borderRadius: BorderRadius.all(
  505. //                                              Radius.circular(5)),
  506. //                                          border: Border.all(
  507. //                                            color: Color(0xFFA4A1B5),
  508. //                                          )),
  509. //                                      child: Center(
  510. //                                        child: _image == null
  511. //                                            ? Text(
  512. //                                                localization.tapToUploadImage,
  513. //                                                textAlign: TextAlign.center,
  514. //                                                style: TextStyle(
  515. //                                                    fontSize: 16,
  516. //                                                    color: Color(0xFFA4A1B5)),
  517. //                                              )
  518. //                                            : Image.file(_image),
  519. //                                      ),
  520. //                                    ),
  521. //                                  ),
  522. //                                ],
  523. //                              ),
  524. //                            )),
  525. //                      ],
  526. //                    ),
  527. //                  ),
  528.                     Padding(
  529.                       padding: EdgeInsets.only(
  530.                           top: deviceSize.height * LISTTOPPADDING * 1.5,
  531.                           bottom: deviceSize.height * BUTTONBOTTOMPADDING),
  532.                       child: this.submitting
  533.                           ? Container(
  534.                               height: 50.0,
  535.                               child: Column(
  536.                                 mainAxisAlignment: MainAxisAlignment.center,
  537.                                 children: <Widget>[
  538.                                   CupertinoActivityIndicator(
  539.                                     radius: 10,
  540.                                   ),
  541.                                 ],
  542.                               ))
  543.                           : CupertinoButton(
  544.                               minSize: 0,
  545.                               padding: EdgeInsets.all(0),
  546.                               onPressed: disabledSubmit
  547.                                   ? null
  548.                                   : () {
  549.                                       handleCreate(deviceSize);
  550.                                     },
  551.                               color: CupertinoTheme.of(context).primaryColor,
  552.                               borderRadius: BorderRadius.circular(30.0),
  553.                               child: Container(
  554.                                   height: 50.0,
  555.                                   child: Center(
  556.                                     child: Text(
  557.                                       localization.register.toUpperCase(),
  558.                                       style: TextStyle(
  559.                                           color: CupertinoColors.white,
  560.                                           fontSize: 17),
  561.                                     ),
  562.                                   ))),
  563.                     ),
  564.                   ],
  565.                 ),
  566.               ),
  567.             );
  568.           }),
  569.         )),
  570.       ),
  571.     );
  572.   }
  573. }
  574.  
  575. //class Region {
  576. //  final String code;
  577. //  final String name;
  578. //
  579. //  Country({this.code, this.name});
  580. //
  581. //  factory Country.fromJson(Map<String, dynamic> json) {
  582. //    return Country(
  583. //      code: json['countryCode'],
  584. //      name: json['countryName'],
  585. //    );
  586. //  }
  587. //}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement