Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:convert';
- import 'package:flutter/material.dart';
- import 'package:flutter_prismahr/helpers/form/ensure_visible_when_focused.dart';
- import 'package:flutter_prismahr/pages/home_page.dart';
- import 'package:http/http.dart' as http;
- import 'package:shared_preferences/shared_preferences.dart';
- class LoginPage extends StatefulWidget {
- LoginPage({Key key}) : super(key: key);
- @override
- _LoginPageState createState() => _LoginPageState();
- }
- class _LoginPageState extends State<LoginPage> {
- bool _isError = false;
- final ScrollController _scsvController = ScrollController();
- final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
- final Map<String, dynamic> formData = {'email': null, 'password': null};
- FocusNode _emailAddressFocusNode = FocusNode();
- FocusNode _passwordFocusNode = FocusNode();
- @override
- void initState() {
- super.initState();
- _isError = false;
- }
- void _setAccessToken(token) async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- prefs.setString('accessToken', 'Bearer $token');
- }
- void _onSubmit() async {
- var url = "http://prismahr-backend.test/api/auth/login";
- if (_formKey.currentState.validate()) {
- _formKey.currentState.save();
- var response = await http.post(url, body: formData);
- var decoded = jsonDecode(response.body);
- print('Status Code: ${response.statusCode}');
- print('Access Token: ${decoded["access_token"]}');
- if (response.statusCode != 200) {
- setState(() {
- _isError = true;
- });
- } else {
- _setAccessToken(decoded['access_token']);
- Navigator.pushReplacement(
- context, MaterialPageRoute(builder: (context) => HomePage()));
- }
- }
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- body: SafeArea(
- child: SingleChildScrollView(
- controller: _scsvController,
- child: Container(
- height: MediaQuery.of(context).size.height,
- padding: EdgeInsets.fromLTRB(20.0, 50.0, 20.0, 100.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- Container(
- width: double.infinity,
- child: Column(
- children: <Widget>[
- Container(
- padding: EdgeInsets.only(bottom: 15.0),
- child: Image.asset('images/logo.png', width: 195),
- ),
- Text('Please login to continue')
- ],
- ),
- ),
- Container(
- width: double.infinity,
- child: Form(
- key: _formKey,
- child: Column(
- children: <Widget>[
- _isError == true ? _showAlert(context) : Container(),
- Container(
- margin: EdgeInsets.only(bottom: 20.0),
- child: EnsureVisibleWhenFocused(
- focusNode: _emailAddressFocusNode,
- child: TextFormField(
- focusNode: _emailAddressFocusNode,
- keyboardType: TextInputType.emailAddress,
- textInputAction: TextInputAction.next,
- decoration: const InputDecoration(
- labelText: 'Email Address',
- ),
- validator: (String value) {
- if (!RegExp(
- 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])?")
- .hasMatch(value))
- return 'Please enter a valid email address';
- else if (value.isEmpty)
- return 'Email address is required';
- else
- return null;
- },
- onSaved: (String value) {
- formData['email'] = value;
- },
- onFieldSubmitted: (v) {
- FocusScope.of(context)
- .requestFocus(_passwordFocusNode);
- },
- ),
- ),
- ),
- Container(
- margin: EdgeInsets.only(bottom: 20.0),
- child: EnsureVisibleWhenFocused(
- focusNode: _passwordFocusNode,
- child: TextFormField(
- focusNode: _passwordFocusNode,
- obscureText: true,
- keyboardType: TextInputType.visiblePassword,
- textInputAction: TextInputAction.go,
- decoration: const InputDecoration(
- labelText: 'Password',
- ),
- validator: (String value) {
- if (value.isEmpty)
- return 'Password is required';
- else
- return null;
- },
- onSaved: (String value) {
- formData['password'] = value;
- },
- onFieldSubmitted: (v) {
- _onSubmit();
- },
- ),
- ),
- ),
- Container(
- margin: EdgeInsets.only(bottom: 60.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- GestureDetector(
- onTap: () {},
- child: Text(
- 'Forgot Password?',
- style: TextStyle(
- color: Theme.of(context).primaryColor,
- ),
- ),
- ),
- RaisedButton(
- onPressed: () => _onSubmit,
- elevation: 0.0,
- color: Theme.of(context).primaryColor,
- textColor: Colors.white,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8.0)),
- child: Padding(
- padding: EdgeInsets.symmetric(
- vertical: 20.0, horizontal: 40.0),
- child: Text('Login'),
- ),
- ),
- ],
- ),
- ),
- Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Container(
- margin: EdgeInsets.only(bottom: 20.0),
- child: Text("Don't have account?"),
- ),
- SizedBox(
- width: double.infinity,
- child: RaisedButton(
- onPressed: () {},
- elevation: 0.0,
- color: Colors.grey[200],
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8.0)),
- child: Padding(
- padding: EdgeInsets.symmetric(
- vertical: 20.0, horizontal: 40.0),
- child: Text('Register'),
- ),
- ),
- ),
- ],
- )
- ],
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
- Widget _showAlert(BuildContext context) {
- return Container(
- padding: EdgeInsets.all(25),
- margin: EdgeInsets.only(bottom: 20.0),
- width: double.infinity,
- decoration: BoxDecoration(
- color: Colors.red,
- borderRadius: BorderRadius.circular(8.0),
- ),
- child: Text(
- 'Invalid email or password',
- style: TextStyle(color: Colors.white),
- textAlign: TextAlign.center,
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement