Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 9.43 KB | None | 0 0
  1. import 'dart:convert';
  2.  
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter_prismahr/helpers/form/ensure_visible_when_focused.dart';
  5. import 'package:flutter_prismahr/pages/home_page.dart';
  6. import 'package:http/http.dart' as http;
  7. import 'package:shared_preferences/shared_preferences.dart';
  8.  
  9. class LoginPage extends StatefulWidget {
  10.   LoginPage({Key key}) : super(key: key);
  11.  
  12.   @override
  13.   _LoginPageState createState() => _LoginPageState();
  14. }
  15.  
  16. class _LoginPageState extends State<LoginPage> {
  17.   bool _isError = false;
  18.  
  19.   final ScrollController _scsvController = ScrollController();
  20.   final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  21.   final Map<String, dynamic> formData = {'email': null, 'password': null};
  22.  
  23.   FocusNode _emailAddressFocusNode = FocusNode();
  24.   FocusNode _passwordFocusNode = FocusNode();
  25.  
  26.   @override
  27.   void initState() {
  28.     super.initState();
  29.     _isError = false;
  30.   }
  31.  
  32.   void _setAccessToken(token) async {
  33.     SharedPreferences prefs = await SharedPreferences.getInstance();
  34.     prefs.setString('accessToken', 'Bearer $token');
  35.   }
  36.  
  37.   void _onSubmit() async {
  38.     var url = "http://prismahr-backend.test/api/auth/login";
  39.  
  40.     if (_formKey.currentState.validate()) {
  41.       _formKey.currentState.save();
  42.  
  43.       var response = await http.post(url, body: formData);
  44.       var decoded = jsonDecode(response.body);
  45.  
  46.       print('Status Code: ${response.statusCode}');
  47.       print('Access Token: ${decoded["access_token"]}');
  48.  
  49.       if (response.statusCode != 200) {
  50.         setState(() {
  51.           _isError = true;
  52.         });
  53.       } else {
  54.         _setAccessToken(decoded['access_token']);
  55.  
  56.         Navigator.pushReplacement(
  57.             context, MaterialPageRoute(builder: (context) => HomePage()));
  58.       }
  59.     }
  60.   }
  61.  
  62.   @override
  63.   Widget build(BuildContext context) {
  64.     return Scaffold(
  65.       body: SafeArea(
  66.         child: SingleChildScrollView(
  67.           controller: _scsvController,
  68.           child: Container(
  69.             height: MediaQuery.of(context).size.height,
  70.             padding: EdgeInsets.fromLTRB(20.0, 50.0, 20.0, 100.0),
  71.             child: Column(
  72.               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  73.               crossAxisAlignment: CrossAxisAlignment.center,
  74.               children: <Widget>[
  75.                 Container(
  76.                   width: double.infinity,
  77.                   child: Column(
  78.                     children: <Widget>[
  79.                       Container(
  80.                         padding: EdgeInsets.only(bottom: 15.0),
  81.                         child: Image.asset('images/logo.png', width: 195),
  82.                       ),
  83.                       Text('Please login to continue')
  84.                     ],
  85.                   ),
  86.                 ),
  87.                 Container(
  88.                   width: double.infinity,
  89.                   child: Form(
  90.                     key: _formKey,
  91.                     child: Column(
  92.                       children: <Widget>[
  93.                         _isError == true ? _showAlert(context) : Container(),
  94.                         Container(
  95.                           margin: EdgeInsets.only(bottom: 20.0),
  96.                           child: EnsureVisibleWhenFocused(
  97.                             focusNode: _emailAddressFocusNode,
  98.                             child: TextFormField(
  99.                               focusNode: _emailAddressFocusNode,
  100.                               keyboardType: TextInputType.emailAddress,
  101.                               textInputAction: TextInputAction.next,
  102.                               decoration: const InputDecoration(
  103.                                 labelText: 'Email Address',
  104.                               ),
  105.                               validator: (String value) {
  106.                                 if (!RegExp(
  107.                                         r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
  108.                                     .hasMatch(value))
  109.                                   return 'Please enter a valid email address';
  110.                                 else if (value.isEmpty)
  111.                                   return 'Email address is required';
  112.                                 else
  113.                                   return null;
  114.                               },
  115.                               onSaved: (String value) {
  116.                                 formData['email'] = value;
  117.                               },
  118.                               onFieldSubmitted: (v) {
  119.                                 FocusScope.of(context)
  120.                                     .requestFocus(_passwordFocusNode);
  121.                               },
  122.                             ),
  123.                           ),
  124.                         ),
  125.                         Container(
  126.                           margin: EdgeInsets.only(bottom: 20.0),
  127.                           child: EnsureVisibleWhenFocused(
  128.                             focusNode: _passwordFocusNode,
  129.                             child: TextFormField(
  130.                               focusNode: _passwordFocusNode,
  131.                               obscureText: true,
  132.                               keyboardType: TextInputType.visiblePassword,
  133.                               textInputAction: TextInputAction.go,
  134.                               decoration: const InputDecoration(
  135.                                 labelText: 'Password',
  136.                               ),
  137.                               validator: (String value) {
  138.                                 if (value.isEmpty)
  139.                                   return 'Password is required';
  140.                                 else
  141.                                   return null;
  142.                               },
  143.                               onSaved: (String value) {
  144.                                 formData['password'] = value;
  145.                               },
  146.                               onFieldSubmitted: (v) {
  147.                                 _onSubmit();
  148.                               },
  149.                             ),
  150.                           ),
  151.                         ),
  152.                         Container(
  153.                           margin: EdgeInsets.only(bottom: 60.0),
  154.                           child: Row(
  155.                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
  156.                             children: <Widget>[
  157.                               GestureDetector(
  158.                                 onTap: () {},
  159.                                 child: Text(
  160.                                   'Forgot Password?',
  161.                                   style: TextStyle(
  162.                                     color: Theme.of(context).primaryColor,
  163.                                   ),
  164.                                 ),
  165.                               ),
  166.                               RaisedButton(
  167.                                 onPressed: () => _onSubmit,
  168.                                 elevation: 0.0,
  169.                                 color: Theme.of(context).primaryColor,
  170.                                 textColor: Colors.white,
  171.                                 shape: RoundedRectangleBorder(
  172.                                     borderRadius: BorderRadius.circular(8.0)),
  173.                                 child: Padding(
  174.                                   padding: EdgeInsets.symmetric(
  175.                                       vertical: 20.0, horizontal: 40.0),
  176.                                   child: Text('Login'),
  177.                                 ),
  178.                               ),
  179.                             ],
  180.                           ),
  181.                         ),
  182.                         Column(
  183.                           crossAxisAlignment: CrossAxisAlignment.start,
  184.                           children: <Widget>[
  185.                             Container(
  186.                               margin: EdgeInsets.only(bottom: 20.0),
  187.                               child: Text("Don't have account?"),
  188.                             ),
  189.                             SizedBox(
  190.                               width: double.infinity,
  191.                               child: RaisedButton(
  192.                                 onPressed: () {},
  193.                                 elevation: 0.0,
  194.                                 color: Colors.grey[200],
  195.                                 shape: RoundedRectangleBorder(
  196.                                     borderRadius: BorderRadius.circular(8.0)),
  197.                                 child: Padding(
  198.                                   padding: EdgeInsets.symmetric(
  199.                                       vertical: 20.0, horizontal: 40.0),
  200.                                   child: Text('Register'),
  201.                                 ),
  202.                               ),
  203.                             ),
  204.                           ],
  205.                         )
  206.                       ],
  207.                     ),
  208.                   ),
  209.                 ),
  210.               ],
  211.             ),
  212.           ),
  213.         ),
  214.       ),
  215.     );
  216.   }
  217.  
  218.   Widget _showAlert(BuildContext context) {
  219.     return Container(
  220.       padding: EdgeInsets.all(25),
  221.       margin: EdgeInsets.only(bottom: 20.0),
  222.       width: double.infinity,
  223.       decoration: BoxDecoration(
  224.         color: Colors.red,
  225.         borderRadius: BorderRadius.circular(8.0),
  226.       ),
  227.       child: Text(
  228.         'Invalid email or password',
  229.         style: TextStyle(color: Colors.white),
  230.         textAlign: TextAlign.center,
  231.       ),
  232.     );
  233.   }
  234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement