import 'package:flutter/material.dart'; import 'package:logger/logger.dart'; import 'package:shared_preferences/shared_preferences.dart'; final log = Logger(); class CredentialsForm extends StatefulWidget { CredentialsForm({@required this.defaultNextRoute, Key key}) : super(key: key); final String defaultNextRoute; @override _CredentialsState createState() => _CredentialsState(); } class _CredentialsState extends State { static String title = "Credentials"; String username; String password; bool _hidden = true; final _credFormKey = GlobalKey(); final _scaffoldKey = GlobalKey(); InputDecoration _textFieldDecoration(String label, IconData icon) { return InputDecoration( labelText: label, icon: Icon(icon), hintText: 'Please, insert your zucchetti account $label', ); } String validateUsername(String username) { if (username.isEmpty) { return 'Username must not be empty'; } return null; } String validatePassword(String password) { if (password.isEmpty) { return 'Password must not be empty'; } return null; } Future getNextRoute() async { var persistence = await SharedPreferences.getInstance(); String nextRoute = persistence.getString("nextRoute"); if (nextRoute != null) { log.d("nextRoute: $nextRoute"); return nextRoute; } log.d("defaultNextRoute: ${widget.defaultNextRoute}"); return null; } Future _onPressed() async { var persistence = await SharedPreferences.getInstance(); if (_credFormKey.currentState.validate()) { _scaffoldKey.currentState .showSnackBar(SnackBar(content: Text('Processing Data'))); } _credFormKey.currentState.save(); log.d("username: ${this.username}\tpassword: ${this.password}"); persistence.setString("username", this.username); persistence.setString("password", this.password); String nextRoute = await getNextRoute(); if (nextRoute == null) { Navigator.pushNamedAndRemoveUntil( context, widget.defaultNextRoute, (Route route) => false); } else { Navigator.pushNamed(context, nextRoute); } } Form theForm() => Form( key: _credFormKey, child: Column(children: [ TextFormField( autofocus: true, autocorrect: false, decoration: this._textFieldDecoration("username", Icons.alternate_email), validator: this.validateUsername, onSaved: (String user) { username = user; }), TextFormField( autocorrect: false, decoration: this._textFieldDecoration("password", Icons.lock), validator: this.validatePassword, obscureText: this._hidden, onSaved: (String pass) { password = pass; }), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ RaisedButton( onPressed: this._onPressed, child: Text('Validate'), ), Row(children: [ Text('Reveal password'), Checkbox( value: !this._hidden, onChanged: (bool value) { setState(() { _hidden = !value; }); return; }) ]) ]), ])); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar(title: Text(title)), body: theForm()); } }