Flutter: Password Check - flutter

I will enter the password to the user 2 times. but i don't know how to check this. How can I be sure that both passwords are spelled the same? can i do this?
here is my code,(I just put the relevant parts in order not to be long)
class _RegisterPageState extends State<RegisterPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
_paddingPasswordWidget('Password', 'Password'),
_paddingPasswordWidget('Password Again', 'Password Again'),
],
),
),
),
);
}
}
_paddingPasswordWidget(String hintTextStr, String labelTextStr) {
return Padding(
padding: EdgeInsets.only(top: 15, left: 22, right: 22),
child: TextFormField(
keyboardType: TextInputType.text,
style: TextStyle(
color: HexColor('#868686'),
),
decoration: CommonInputStyle.textFieldStyle(
hintTextStr: hintTextStr,
labelTextStr: labelTextStr,
),
obscureText: true,
),
);
}
class CommonInputStyle {
static InputDecoration textFieldStyle(
{String labelTextStr = "", String hintTextStr = ""}) {
return InputDecoration(
contentPadding: EdgeInsets.only(left: 20, top: 5, bottom: 5, right: 20),
labelText: labelTextStr,
hintText: hintTextStr,
labelStyle: TextStyle(fontSize: 14, color: HexColor('#868686')),
hintStyle: TextStyle(fontSize: 14, color: HexColor('#868686')),
filled: true,
fillColor: HexColor('#EEF2F4'),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
);
}
}

You can try putting textEditingController in your fields, then you compare them. Something like this:
var textFieldPasswordController = TextEditingController();
var textFieldConfirmPasswordController = TextEditingController();
then you pass these as controllers in your TextFormField:
TextFormField(
controller: textFieldPasswordController //as an example
keyboardType: TextInputType.text,
style: TextStyle(
color: HexColor('#868686'),
),
Now you just need to check if textFieldPasswordController.text equals to textFieldConfirmPasswordController.text. You can check this in the onChange or validator function of TextFormField
if(textFieldPasswordController.text == textFieldConfirmPasswordController.text){
print("Access granted");
} else{
print("Try again");
}

Related

Flutter Textformfield should be responsive to typing and error

I've often seen where fields are responsive when users are typing, giving realtime feedback. An example is when I'm typing confirm password or email, if the confirm password or email hasn't matched the password while typing it returns error by marking turning the border of the field red until it matches the correct input. I have written this code, how do I improve the code to be responsive as described.
Widget _buildConfirmPasswordTF() {
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
// Text('Password', style: kLabelStyle,),
SizedBox(height: 10.0),
Container(alignment: Alignment.centerLeft, decoration: kBoxDecorationStyle, height: 60.0, child: TextFormField(
validator: ( confirmPassword ){
if ( confirmPassword.trim() != _password.isValidPassword ) {
return null;
} else {
return 'Password doesn\'t match';
}
},
obscureText: true, style: TextStyle(color: Colors.white, fontFamily: 'OpenSans',),
decoration: InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(Icons.lock, color: Colors.white,),
hintText: 'Enter Confirm Password',
hintStyle: kHintTextStyle,
errorBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.red ) ),
focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( color: Colors.red ) )
),
),
),
],
);
}
This is where I set the hintText
final kHintTextStyle = TextStyle(
color: Colors.white54,
fontFamily: 'OpenSans',
);
This is where I set the labelStyle
final kLabelStyle = TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontFamily: 'OpenSans',
);
This is where I set the border decoration
final kBoxDecorationStyle = BoxDecoration(
color: Color(0xFF6CA8F1),
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 6.0,
offset: Offset(0, 2),
),
],
);
you need autovalidateMode: AutovalidateMode.onUserInteraction, pass this in textformfield.
You can do that with a Form() providing it a key and a autoValidateMode to make sure the fields have value or that the value is something you except, you can add another field to confirm the passwork or email and compare the value of the field in the onChanged with the value of the other email field to make sure they match.
import 'package:email_validator/email_validator.dart';
final formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool isValid = false;
_emailController.addListener(
() {
//With this, you can "listen" all the changes on your text while
//you are typing on input
//use setState to rebuild the widget
if (EmailValidator.validate(_emailController.text)) {
setState(() {
isValid = true;
});
} else {
setState(() {
isValid = false;
});
}
},
);
Form(
key: formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(
horizontal: size.width * 0.105),
child: TextFormField(
validator: (value) =>
!EmailValidator.validate(value)
? 'Enter a valid email'
: null,
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
controller: _emailController,
decoration: kInputDecoration.copyWith(
hintText: 'Enter your email'),
),
),
SizedBox(
height: 18,
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: size.width * 0.105),
child: TextFormField(
obscureText: true,
validator: (value) =>
value.isEmpty ? 'Enter your password' : null,
keyboardType: TextInputType.text,
textAlign: TextAlign.center,
controller: _passwordController,
decoration: kInputDecoration.copyWith(
hintText: 'Enter your password'),
),
),
],
),
),

Flutter show error when Password not match

I want to validate the passwords. The Widget _buildRepeatPasswordTF, has a TextFormField that validates if the value is not equal to the controller from _buildPasswordTF().
Widget _buildPasswordTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: < Widget > [
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextField(
controller: _passwordController,
obscureText: true,
style: TextStyle(
color: Color.fromRGBO(0, 128, 128, 1),
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
color: Color.fromRGBO(0, 128, 128, 1),
),
hintText: 'Password',
hintStyle: kHintTextStyle,
),
),
),
],
);
}
Widget _buildRepeatPasswordTF() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
controller: _repeatPasswordController,
obscureText: true,
style: TextStyle(
color: Color.fromRGBO(0, 128, 128, 1),
fontFamily: 'OpenSans',
),
validator: (value) {
if (value != _passwordController.text) {
return 'The password doesnt match';
}
return null;
},
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
color: Color.fromRGBO(0, 128, 128, 1),
),
hintText: 'Repeat password',
hintStyle: kHintTextStyle,
),
),
),
],
);
}
Widget _buildSignUpBtn() {
return Container(
padding: EdgeInsets.symmetric(vertical: 25.0),
width: double.infinity,
child: RaisedButton(
elevation: 5.0,
onPressed: () async {
var password = _passwordController.text;
var email = _emailController.text;
var nom = _nameController.text;
var cognoms = _cognomsController.text;
try {
var r = await _provider.attemptSignUp(email, password, nom, cognoms, interessos, sexe, dataNeixement);
if(r['success'] == false) {
displayDialog(context, "Error", r['data']['message']);
}
else {
displayDialog(context, "Registrat", "Verifica el correu.").then((val) {
Navigator.of(context).pop();
});
}
} catch (err) {
displayDialog(context, "Error", err.response.toString());
}
},
padding: EdgeInsets.all(15.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Color.fromRGBO(0, 128, 128, 1),
child: Text(
'Registrar-se',
style: TextStyle(
color: Colors.white,
letterSpacing: 1.5,
fontSize: 18.0,
fontWeight: FontWeight.bold,
fontFamily: 'OpenSans',
),
),
),
);
}
You have missed a main Form and GlobalKeys.
Here a complete functional sample:
import 'package:flutter/material.dart';
class Password extends StatefulWidget {
#override
_PasswordState createState() => _PasswordState();
}
class _PasswordState extends State<Password> {
final TextEditingController _password = TextEditingController();
final TextEditingController _confirmPassword = TextEditingController();
final GlobalKey<FormState> _form = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(30),
child: Form(
key: _form,
child: Column(children: <Widget>[
TextFormField(
controller: _password,
validator: (validator) {
if (validator.isEmpty) return 'Empty';
return null;
}),
TextFormField(
controller: _confirmPassword,
validator: (validator) {
if (validator.isEmpty) return 'Empty';
if (validator != _password.text)
return 'The passwords do not match';
return null;
}),
RaisedButton(
child: Text(
'Registrar-se',
),
elevation: 5.0,
onPressed: () async {
_form.currentState.validate();
})
])),
);
}
}
I also have made a validation more sophisticated using RxDart and Streams. Check it out on medium

Showing TextField's error text does not work

I'm building the changePassword module on an app and I want to check that the field its not empty but its not working and I don't know why
Card(
color: Color(0xFFDBE2EF),
margin: EdgeInsets.symmetric(
vertical: 10, horizontal: 25),
child: TextField(
controller: passwordConfirmController,
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Confirmar contraseña',
labelStyle:
TextStyle(fontFamily: 'Montserrat')),
),
),
SizedBox(
height: 20,
),
RaisedButton(
color: Color(0xFFDBE2EF),
onPressed: () => {
setState(() {
print("Valor _validate antes");
print(_validate);
print("Valor isEmpty");
print(passwordController.text.isEmpty);
passwordController.text.isEmpty
? _validate = true
: _validate = false;
_isLoading = true;
print("Valor _validate después");
print(_validate);
}),
changePass(passwordController.text),
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Text(
'Actualizar',
style: TextStyle(
fontSize: 20,
fontFamily: 'Montserrat',
color: Color(0xFF002D53),
fontWeight: FontWeight.bold),
)),
The values on raisedbutton where I check if the password is empty seems to be working printing the expected values, but the error text does not work
You need to pass the error text to the TextField
TextField(
decoration: InputDecoration(
errorText:"some error",
),
You have to change _validate property inside setState(), and based on that change TextField error text
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
final passwordConfirmController = TextEditingController();
bool _validate = false;
void _validatePassword() {
if (passwordConfirmController.text.isEmpty) {
_validate = true;
} else {
_validate = false;
}
setState(() {
_validate;
print("Valor _validate después");
print(_validate);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: <Widget>[
Card(
color: Color(0xFFDBE2EF),
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
child: TextField(
controller: passwordConfirmController,
obscureText: true,
decoration: InputDecoration(
errorText: _validate ? "Enter Password" : null,
border: OutlineInputBorder(),
labelText: 'Confirmar contraseña',
labelStyle: TextStyle(fontFamily: 'Montserrat')),
),
),
SizedBox(
height: 20,
),
RaisedButton(
color: Color(0xFFDBE2EF),
onPressed: () => {_validatePassword()},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Text(
'Actualizar',
style: TextStyle(
fontSize: 20,
fontFamily: 'Montserrat',
color: Color(0xFF002D53),
fontWeight: FontWeight.bold),
)),
],
),
);
}
}

Flutter replace "," with "."

I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.
I am trying this
double alphareceipe = double.parse(_alphareceipe.text);
alphareceipe = alphareceipe.replace("," ".");
But get this error:
error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).
The total code looks like this:
import 'package:flutter/material.dart';
import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';
const String testDevice = "Mobile_id";
class AlphaAcid extends StatefulWidget {
#override
_AlphaAcidState createState() => _AlphaAcidState();
}
class _AlphaAcidState extends State<AlphaAcid> {
}
String _emiResult = "";
final TextEditingController _weight = TextEditingController();
final TextEditingController _alphareceipe = TextEditingController();
final TextEditingController _alphanew = TextEditingController();
#override
void initState() {
initPlatformState();
super.initState();
}
#override
String _locale;
Future<void> initPlatformState() async {
String currentLocale;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
currentLocale = await Devicelocale.currentLocale;
print(currentLocale);
} on PlatformException {
print("Error obtaining current locale");
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_locale = currentLocale;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
backgroundColor: Colors.green[800],
//elevation: 0.0,
),
body: Center(
child: Container(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _alphareceipe,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
labelText: _locale != 'da-DK'
? "Alpha acid receipe"
: "Alpha syre opskrift",
labelStyle: TextStyle(color: Colors.green[800])
),
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
// WhitelistingTextInputFormatter.digitsOnly
],
),
),
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _alphanew,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
//labelText: "Final Gravity (1018)",
labelText: _locale != 'da-DK'
? "Your alpha acid"
: "Din alpha syre",
labelStyle: TextStyle(color: Colors.green[800]),
),
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
//WhitelistingTextInputFormatter.digitsOnly
],
),
),
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _weight,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
//labelText: "Final Gravity (1018)",
labelText: _locale != 'da-DK'
? "Weight receipe"
: "Vægt i opskrift",
labelStyle: TextStyle(color: Colors.green[800]),
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
),
),
Flexible(
fit: FlexFit.loose,
child: FlatButton(
onPressed: _handleCalculation,
//child: Text("Calculate"),
child: Text(AppLocalizations.of(context).translate('calculate'),),
color: Colors.green[600],
textColor: Colors.white,
padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),
),
),
emiResultsWidget(_emiResult)
],
),
),
));
}
void _handleCalculation() {
double newWeight = 0.0;
//
//
//
//
//
double alphareceipe = double.parse(_alphareceipe.text);
alphareceipe = alphareceipe.replace("," ".");
int alphanew =int.parse(_alphanew.text);
int weightreceipe = int.parse(_weight.text);
//
try {
newWeight = (weightreceipe * alphareceipe) / alphanew;
_emiResult = newWeight.toStringAsFixed(0);
setState(() {
});
} //catch(e) {
on Exception catch(e){
print(e);
setState(() {
});
}
//_emiResult = A.toStringAsFixed(1);
//setState(() {
//});
}
Widget emiResultsWidget(emiResult) {
bool canShow = false;
String _emiResult = emiResult;
if(_emiResult.length > 0) {
canShow = true;
}
return
Container(
margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
alignment: FractionalOffset.center,
color: Colors.green[50],
child: canShow ? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
//crossAxisAlignment: CrossAxisAlignment.start,
//mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget> [
Padding(
padding: EdgeInsets.all(10.0),
child:
Text(AppLocalizations.of(context).translate('newweight'),
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.green[800],
),
)
),
SizedBox(width: 20.0,),
Text(_emiResult,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.green[800],
)
),
SizedBox(width: 10.0,),
]),
]
) : Container(),
);
}
}
I would suggest to use an appropriate keyboard type in combination with an input formatter.
keyboardType: TextInputType.numberWithOptions(decimal: allowDecimal),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0-9]+[,.]{0,1}[0-9]*')),
TextInputFormatter.withFunction(
(oldValue, newValue) => newValue.copyWith(
text: newValue.text.replaceAll(',', '.'),
),
),
],
This way, the user can only enter digits and ",", ".", "-" and even if a "," is entered, the second input formatter (they can be chained) replaces the ",". All this happens while this is still a String and not a number.
You cannot use a String function on a double. Replace the symbol on the String, then cast to double.
You are trying to replace the characters after the text has already been converted to a double. Try this instead:
double alphareceipe = double.parse(_alphareceipe.text.replaceAll(",", "."));

How to add country dial code to TextEditingController in flutter

I'm using flutter package country_code_picker into my TextFormField and i achieve to put users country dial code into my phone TextEditingController text after they select there country. So if for example in Senegal user put 7712345678, i will get +2217712345678 in my TextEditing controller text. Thanks in advance for help.
here is my code
TextEditingController phoneController = new TextEditingController(text: "");
Widget _phoneContainer() {
return new Container(
child: new TextFormField(
controller: phoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 2),
prefixIcon: CountryCodePicker(
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: '+221',
favorite: ['+221', 'SN'],
textStyle: TextStyle(color: Colors.orange[900]),
showFlag: true,
//showFlagDialog: true,
//comparator: (a, b) => b.name.compareTo(a.name),
//Get the country information relevant to the initial selection
//onInit: (code) => print("${code.name} ${code.dialCode}"),
),
labelText: Texts.PHONE_NUMBER_LOGIN,
focusColor: Colors.orange[900],
labelStyle: TextStyle(fontSize: 15.0, color: Colors.orange[900]),
/* hintStyle: TextStyle(
color: Colors.orange[900]
) */
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
hasFloatingPlaceholder: false
),
keyboardType: TextInputType.phone,
style:TextStyle(
color: Colors.orange[900],
decorationColor: Colors.white,
),
),
margin: EdgeInsets.only(bottom: 20.0, left: 40.0, right: 40.0),
color: Colors.white,
height: 40.0,
);
}
Run this code. On Check Button, it will print your whole phone number (dial code + entered phone number in text field) on console
import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
TextEditingController phoneController = new TextEditingController();
String phoneNumber = "";
void _onCountryChange(CountryCode countryCode) {
this.phoneNumber = countryCode.toString();
print("New Country selected: " + countryCode.toString());
}
void check(){
print("Full Text: "+ this.phoneNumber + phoneController.text);
}
#override
Widget build(BuildContext context) {
final phone = new TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
autofocus: false,
style: new TextStyle(fontSize:14.0,
color: Colors.black,
fontWeight: FontWeight.w400,),
);
final checkBtn = RaisedButton(key: null, onPressed: check,
color: Colors.blue,
child: new Text("Check")
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Country Code Demo'),
),
body: Center(
child: new ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
CountryCodePicker(
onChanged: _onCountryChange,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT',
favorite: ['+39','FR'],
// optional. Shows only country name and flag
showCountryOnly: false,
// optional. Shows only country name and flag when popup is closed.
showOnlyCountryWhenClosed: false,
// optional. aligns the flag and the Text left
alignLeft: false,
),
SizedBox(height: 16.0),
phone,
SizedBox(height: 16.0),
checkBtn
]
),
),
)
);
}
}