Advertisement
Guest User

Untitled

a guest
Sep 10th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 6.68 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:apetrus/utils/Constantes.dart' as Constantes;
  3. import 'package:shared_preferences/shared_preferences.dart';
  4. import 'home_page.dart';
  5. import 'package:http/http.dart' as http;
  6. import 'dart:convert';
  7. import 'dart:async';
  8.  
  9. class LoginPage extends StatefulWidget {
  10.   @override
  11.   _LoginPageState createState() => _LoginPageState();
  12. }
  13.  
  14. class _LoginPageState extends State<LoginPage> {
  15.  
  16.   SharedPreferences prefs;
  17.   bool checkvalue = false;
  18.   TextEditingController usuario = new TextEditingController();
  19.   TextEditingController senha = new TextEditingController();
  20.  
  21.   Map<String, dynamic> retornoJSON;
  22.   bool _isLoading = false;
  23.   final formKey = new GlobalKey<FormState>();
  24.   final scaffoldKey = new GlobalKey<ScaffoldState>();
  25.   String _usuario, _senha;
  26.  
  27.   @override
  28.   initState() {
  29.     _getDadosSalvos();
  30.     super.initState();
  31.   }
  32.  
  33.   void _submit() {
  34.     final form = formKey.currentState;
  35.     if(form.validate()) {
  36.       form.save();
  37.       setState(() {
  38.         _isLoading = true;
  39.       });
  40.       _validaLogin(_usuario, _senha);
  41.     }
  42.   }
  43.  
  44.   _getDadosSalvos() async {
  45.     prefs = await SharedPreferences.getInstance();
  46.     setState(() {
  47.       checkvalue = (prefs.getBool("_checkvalue") ?? false);
  48.       usuario.text = (prefs.getString("_usuario") ?? "");
  49.       senha.text = (prefs.getString("_senha") ?? "");
  50.     });
  51.   }
  52.  
  53.   _salvarLocal() async {
  54.     prefs = await SharedPreferences.getInstance();
  55.     if(checkvalue) {
  56.       setState(() {
  57.         prefs.setString("_usuario", _usuario);
  58.         prefs.setString("_senha", _senha);
  59.         prefs.setBool("_checkvalue", checkvalue);
  60.       });
  61.     } else {
  62.       usuario.clear();
  63.       senha.clear();
  64.       prefs.clear();
  65.     }
  66.   }
  67.  
  68.   // Navigator.of(context).pushNamed('/homepage');
  69.  
  70.   Future<Null> _validaLogin(String email, String senha) async {
  71.     Map<String, String> dadosUser = {
  72.       'email': email,
  73.       'senha': senha
  74.     };
  75.  
  76.     var result = await http.post(Constantes.url + "loginMobile", body: dadosUser);
  77.     String retornoBody = result.body;
  78.     retornoJSON = json.decode(retornoBody);
  79.     if(result.request.finalized) {
  80.       setState(() {
  81.         _isLoading = false;
  82.       });
  83.       if(retornoJSON['result'] == 'erro') {
  84.         _showErro("Ops!","Erro ao acessar, revise seus dados!");
  85.       } else {
  86.         _salvarLocal();
  87.         Navigator.push(
  88.           context,
  89.           MaterialPageRoute(builder: (context) => HomePage(retornoJSON['result'])),
  90.         );
  91.       }
  92.     } else {
  93.       _showErro("Ops!","Não foi possivel carregar!");
  94.       setState(() {
  95.         _isLoading = false;
  96.       });
  97.     }
  98.   }
  99.  
  100.   _showErro(String titulo, String mensagem) {
  101.     showDialog(
  102.         context: context,
  103.         builder: (BuildContext context) {
  104.           return new AlertDialog(
  105.             title: new Text(titulo),
  106.             content: new Text(mensagem),
  107.             actions: <Widget>[
  108.               new FlatButton(
  109.                   onPressed: () => Navigator.of(context).pop(),
  110.                   child: new Text("OK")
  111.               )
  112.             ],
  113.           );
  114.         }
  115.     );
  116.   }
  117.  
  118.   @override
  119.   Widget build(BuildContext context) {
  120.     var loginBtn = new SizedBox(
  121.       width: double.maxFinite,
  122.       child: new RaisedButton(
  123.         shape: new RoundedRectangleBorder(
  124.             borderRadius: new BorderRadius.circular(20.0)
  125.         ),
  126.         onPressed: _submit,
  127.         color: Theme.of(context).primaryColor,
  128.         textColor: Colors.white,
  129.         child: new Text("ENTRAR"),
  130.       ),
  131.     );
  132.  
  133.     var loginForm = new ListView(
  134.       children: <Widget>[
  135.         new Column(
  136.           crossAxisAlignment: CrossAxisAlignment.start,
  137.           children: <Widget>[
  138.             new Container(
  139.               color: const Color(Constantes.CorPadrao),
  140.               width: double.infinity,
  141.               height: 200.0,
  142.               child: new Padding(
  143.                   padding: const EdgeInsets.all(30.0),
  144.                   child: new Image.asset(
  145.                     Constantes.logo
  146.                   ),
  147.               ),
  148.             ),
  149.             new Divider(
  150.                 height: 1.0,
  151.                 color: Theme.of(context).primaryColor,
  152.             ),
  153.             new Padding(
  154.                 padding: const EdgeInsets.all(20.0),
  155.                 child: new Form(
  156.                     key: formKey,
  157.                     child: new Column(
  158.                       children: <Widget>[
  159.                         new TextFormField(
  160.                           controller: usuario,
  161.                           onSaved: (val) => _usuario = val,
  162.                           validator: (val) {
  163.                             return val.isEmpty
  164.                                 ? "Digite seu e-mail"
  165.                                 : null;
  166.                           },
  167.                           decoration: new InputDecoration(labelText: "E-mail"),
  168.                         ),
  169.                         new Padding(
  170.                             padding: const EdgeInsets.only(bottom: 10.0)
  171.                         ),
  172.                         new TextFormField(
  173.                           controller: senha,
  174.                           onSaved: (val) => _senha = val,
  175.                           validator: (val) {
  176.                             return val.isEmpty
  177.                                 ? "Digite sua senha"
  178.                                 : null;
  179.                           },
  180.                           obscureText: true,
  181.                           decoration: new InputDecoration(labelText: "Senha"),
  182.                         ),
  183.                         new Padding(
  184.                             padding: const EdgeInsets.only(bottom: 10.0)
  185.                         ),
  186.                         loginBtn,
  187.                         new Row(
  188.                           mainAxisAlignment: MainAxisAlignment.center,
  189.                           children: <Widget>[
  190.                             new Checkbox(
  191.                                 value: checkvalue,
  192.                                 onChanged: (bool newvalue) {
  193.                                   setState(() {
  194.                                     checkvalue = newvalue;
  195.                                   });
  196.                                 }),
  197.                             new Text("Salvar dados de acesso")
  198.                           ],
  199.                         ),
  200.                       ],
  201.                     )
  202.                 ),
  203.             ),
  204.           ],
  205.         ),
  206.       ],
  207.     );
  208.     var loader = new Center(
  209.       child: new CircularProgressIndicator(),
  210.     );
  211.     return Scaffold(
  212.       appBar: null,
  213.       key: scaffoldKey,
  214.       body: _isLoading ? loader : loginForm,
  215.     );
  216.   }
  217. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement