How to show country code in the container - flutter

I'm working on phone number textfield, so for i got this package, and i want its CustomDecoration style, but i'm not getting it. here is my code.
Widget phonetextformfieldCustomwithouticon(context, width, controller, height) {
return Container(
width: width,
child: InternationalPhoneNumberInput(
inputDecoration: InputDecoration(
contentPadding:EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
},
),
);
}
updated:
I want country should have some padding, becuase it starts from the leftmost, and when i add validation in it, redner flow
Container(
width: MediaQuery.of(context).size.width * 0.9,
height: 55.0,
decoration: BoxDecoration(
border: Border.all(color: HexColor("#6e6b7b")),
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
child: InternationalPhoneNumberInput(
inputDecoration: InputDecoration(
contentPadding:EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
labelText: "Phone number",
labelStyle: GoogleFonts.montserrat(color: HexColor("#6e6b7b")),
hintStyle: GoogleFonts.montserrat(),
hintText: "Enter a phone number",
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 0.0,
))),
// enabledBorder: InputBorder.none,
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.DIALOG,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
// initialValue: number,
textFieldController: contactNo,
formatInput: false,
keyboardType: TextInputType.numberWithOptions(
signed: true, decimal: true),
inputBorder: InputBorder.none,
onSaved: (PhoneNumber number) {
print('On Saved: $number');
},
),
),
here is the output:

Try below code hope its helpful to you.refer package here and example here
create variables:
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController controller = TextEditingController();
String initialCountry = 'NG';
PhoneNumber number = PhoneNumber(isoCode: 'NG');
Create one function for getting number and dispose your controller
void getPhoneNumber(String phoneNumber) async {
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');
setState(() {
this.number = number;
});
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
Your widget:
Container(
padding: EdgeInsets.all(7),
color: Colors.blue,
child: Card(
child: Form(
key: formKey,
child: Container(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
initialValue: number,
textFieldController: controller,
formatInput: false,
keyboardType: TextInputType.numberWithOptions(
signed: true, decimal: true),
inputBorder: InputBorder.none,
onSaved: (PhoneNumber number) {
print('On Saved: $number');
},
),
],
),
),
),
),
),
Your result screen on your need->

I've just written this:
InternationalPhoneNumberInput(
onInputChanged: (val) {},
inputDecoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 0.0,
),
),
enabledBorder: InputBorder.none,
),
),
and it seems like these:
But I couldn't test it on android. Can you try this?

Related

Error when focussing on next Focus in Flutter

If I click away from a TextField and then back on it and want to focus on the next TextField (using FocusScope.of(context).nextFocus()) by hitting enter on the software keyboard I get this error:
Exception has occurred.
_AssertionError ('package:flutter/src/widgets/focus_manager.dart': Failed assertion: line 790 pos 7: 'context != null': Tried to get the bounds of a focus node that didn't have its context set yet.
The context needs to be set before trying to evaluate traversal policies. Setting the context is typically done with the attach method.)
This is my code:
import 'package:quizlet/api/convert_json.dart';
import 'package:quizlet/style.dart';
class CreateQuiz extends StatefulWidget {
const CreateQuiz({super.key});
#override
State<CreateQuiz> createState() => _CreateQuizState();
}
class _CreateQuizState extends State<CreateQuiz> {
int wordCount = 3;
List errorDefinitions = [false, false, false];
List errorAnswers = [false, false, false];
bool errorTitle = false;
bool errorDescription = false;
final List definitions = [
TextEditingController(),
TextEditingController(),
TextEditingController()
];
final List answers = [
TextEditingController(),
TextEditingController(),
TextEditingController()
];
final title = TextEditingController();
final description = TextEditingController();
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
final brightness = MediaQuery.of(context).platformBrightness;
bool darkMode = brightness == Brightness.dark;
final hintColor = darkMode ? Colors.white : Colors.black;
return Scaffold(
appBar: AppBar(
title: const Text("Create Quiz"),
actions: [
TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
),
onPressed: () {
onPressed();
},
child: Text(
"Done",
style: TextStyle(fontSize: height / 55),
),
),
],
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView(
children: [
SizedBox(
height: height / 40,
),
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorTitle = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
keyboardType: TextInputType.multiline,
controller: title,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorTitle ? Colors.red : hintColor,
),
hintText: errorTitle ? "Title can't be blank" : "Title",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorTitle ? Colors.red : color1,
width: 2.0,
),
),
),
),
const SizedBox(
height: 5,
),
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorDescription = false;
});
},
textInputAction: TextInputAction.newline,
onEditingComplete: () {},
controller: description,
maxLines: null,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintText: errorDescription
? "Description can't be blank"
: "Description",
hintStyle: TextStyle(
color: errorDescription ? Colors.red : hintColor,
),
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorDescription ? Colors.red : color1,
width: 2.0,
),
),
),
),
SizedBox(
height: height / 20,
),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: wordCount,
itemBuilder: (BuildContext context, int i) {
return Column(
children: [
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorDefinitions[i] = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
autocorrect: false,
controller: definitions[i],
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorDefinitions[i] ? Colors.red : hintColor,
),
hintText: errorDefinitions[i]
? "Definition can't be blank"
: "Definition",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorDefinitions[i] ? Colors.red : color1,
width: 2.0,
),
),
),
),
const SizedBox(
height: 5,
),
TextField(
onSubmitted: (value) {
setState(() {
if (definitions[i].text != "" &&
answers[i].text != "") {
if (i + 2 >= wordCount) {
wordCount++;
definitions.add(TextEditingController());
answers.add(TextEditingController());
errorAnswers.add(false);
errorDefinitions.add(false);
}
FocusScope.of(context).nextFocus();
}
});
},
onChanged: (value) {
setState(() {
errorAnswers[i] = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
autocorrect: false,
controller: answers[i],
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorAnswers[i] ? Colors.red : hintColor,
),
hintText: errorAnswers[i]
? "Answer can't be blank"
: "Answer",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorAnswers[i] ? Colors.red : color1,
width: 2.0,
),
),
),
),
SizedBox(
height: height / 50,
),
],
);
},
),
],
),
),
),
);
}```

How to get data in a Flutter-ListView?

I'm building a form for shipping and am able to add as many items as possible. (Adding a Widget in a ListView every time a button is pressed)
My question is, once the form widgets are created and filled, how do I get the information from each TextFormField in each Widget?
Once the information is retrieved I will send it to Firebase.
Here's the code I Have:
import 'package:flutter/material.dart';
import 'package:flutter_login_test/helpers/constants.dart';
class AddItemsToRequest extends StatefulWidget {
const AddItemsToRequest({Key? key}) : super(key: key);
#override
State<AddItemsToRequest> createState() => _AddItemsToRequestState();
}
class _AddItemsToRequestState extends State<AddItemsToRequest> {
List<TextEditingController> controllers = [];
List<Widget> fields = [];
RegExp regExp = RegExp('[aA-zZ]');
int quantity = 0;
double weight = 0;
double height = 0;
Widget itemForm() {
return Column(children: [
Container(
decoration:
BoxDecoration(color: grey, border: Border.all(color: black)),
width: double.infinity,
child: const Center(
child: Text('Package details',
style: TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: grey,
fontSize: 24)),
)),
Row(
children: [
Flexible(
child: TextFormField(
onChanged: (value) {
quantity = value as int;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || value is int
? 'Quantity cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Quantity : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
weight = value as double;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || regExp.hasMatch(value)
? 'Weight cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Weight : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
height = value;
},
validator: (value) => value!.isEmpty ? 'Height cannot be empty' : null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Height : "),
),
),
],
),
]);
}
Widget _addTile() {
return ElevatedButton(
child: const Icon(Icons.add),
onPressed: () async {
final controller = TextEditingController();
final field = itemForm();
setState(() {
controllers.add(controller);
fields.add(field);
});
});
}
Widget _listView() {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: fields.length,
itemBuilder: (context, index) {
final item = fields[index];
return Dismissible(
key: ObjectKey(item),
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
fields.removeAt(index);
});
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Package removed')));
},
background: Container(
color: const Color.fromARGB(255, 210, 31, 19),
child: const Center(
child: Text(
'Remove ',
style: TextStyle(
color: white, fontWeight: FontWeight.bold, fontSize: 32),
),
)),
child: Container(
width: double.infinity,
margin: const EdgeInsets.all(5),
child: fields[index],
),
);
},
);
}
Widget _okButton() {
return ElevatedButton(
onPressed: () {
for (var element in fields) {
print(quantity);
}
Navigator.of(context).pop();
print('ok');
},
child: const Text("OK"),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: blue),
body: Column(
mainAxisSize: MainAxisSize.max,
children: [
Flexible(child: _addTile()),
SizedBox(
height: MediaQuery.of(context).size.height - 200,
child: _listView()),
Flexible(child: _okButton()),
],
),
);
}
}
I think you are expecting this answer. iterate your list of texteditingcontroller and get the text stored in that controllers one by one.
for (int i = 0; i < controllers.length; i++) {
var data = controllers[i].text;
//print or add data to any other list and insert to another list and save to database
}

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'),
),
),
],
),
),

How i can put (true icon) while i writing email and verifying from it with flutter

How I can put the icon while typing the email to verifying from email regex and the strength of the password?
TextFormField(
controller: _emailController,
textAlign: TextAlign.end,
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 16),
hintText: "example#gmail.com",
fillColor: Colors.grey[200],
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
borderRadius: BorderRadius.circular(14))),
onSaved: (String value) {
email = value;
},
validator: _validateEmail,
keyboardType: TextInputType.emailAddress,
),
Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 20, 0),
child: Text(
"كلمة المرور",
textAlign: TextAlign.right,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
),
new TextFormField(
controller: _passwordController,
textAlign: TextAlign.end,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
prefixIcon: new GestureDetector(
onTap: () {
setState(() {
_obscureText = !_obscureText;
});
},
child: Padding(
padding:
const EdgeInsets.fromLTRB(20, 10, 0, 0),
child: Icon(
_obscureText
? Icons.visibility
: Icons.visibility_off,
color: visi),
)),
hintStyle: TextStyle(fontSize: 16),
hintText: "",
fillColor: Colors.grey[200],
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
borderRadius: BorderRadius.circular(14))),
onSaved: (String value) {
password = value;
},
validator: _validatePassword,
obscureText: !_obscureText,
),
For email, you can add a listener to your _emailController like:
var _myIcon = Icon.cancel;
void initState() {
super.initState();
// Start listening to changes.
_emailController.addListener(_checkEmail);
}
And then:
_checkEmail() {
bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(_emailController.text);
if(emailValid)
setState(() {
_myIcon=Icons.ok;
});
}
Now add a prefixIcon to your email field with _myIcon value.
For a password with :
Minimum 1 Upper case
Minimum 1 lowercase
Minimum 1 Numeric Number
Minimum 1 Special Character
Common Allow Character ( ! # # $ & * ~ )
and based on this answer you can use a Regex like this:
RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$').hasMatch(_passwordController.text);

Show/Hide Passwords in Flutter's TextFormField

I'm working on a TextFormField to accept passwords. I have set the suffix icon to have IconButton child to detect on click events and to toggle the obscuretext attribute of the TextFormField. The callback function for the iconButton gets called but the TextFormField doesn't get repainted. Any ideas on how to solve this?
static Widget buildTextFormField(String id,
FormFieldValidator<String> validateField,
FormFieldSetter<String> saveField,
InputDecoration decoration,
EdgeInsetsGeometry paddingInfo,
EdgeInsetsGeometry marginInfo,
TextInputType keyboardType,
{bool obscureField:false, double width:328.0,
TextEditingController controller}
){
return Container(
padding: paddingInfo,
margin: marginInfo,
width: width,
child: TextFormField(
key: Key(id),
obscureText: obscureField,
validator: validateField,
onSaved: saveField,
keyboardType: keyboardType,
decoration: decoration,
controller: controller,
),
);
}
InputDecoration passwordDecoration = InputDecoration(
hintText: 'Password',
labelText: 'Enter your password',
suffixIcon:
IconButton(
icon: Icon(
_passwordVisible ? Icons.visibility : Icons.visibility_off,
semanticLabel: _passwordVisible ? 'hide password' : 'show password',
),
onPressed: () {
setState(() {
_passwordVisible ^= true;
//print("Icon button pressed! state: $_passwordVisible"); //Confirmed that the _passwordVisible is toggled each time the button is pressed.
});
}),
labelStyle: TextStyle(
fontFamily: 'Roboto Medium',
fontSize: 12.0,
color: Color(0x99000000),
letterSpacing: 0.4,
),
);
final passwordPaddingInfo = const EdgeInsets.only(top: 15.0, bottom:15.0,
left: 22.0, right:25.0);
this._passwordField = AdministrationComponents.
buildTextFormField('passwordField', validatePassword,
(value) => _password = value, passwordDecoration, passwordPaddingInfo,
null, null, controller:_passwordController,
obscureField: !_passwordVisible);
Try to this
bool _showPassword = false;
void _togglevisibility() {
setState(() {
_showPassword = !_showPassword;
});
}
Textform field code
child: TextFormField(
controller: _passwordController,
obscureText: !_showPassword,
cursorColor: Colors.red,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: "Password",
border: InputBorder.none,
suffixIcon: GestureDetector(
onTap: () {
_togglevisibility();
},
child: Icon(
_showPassword ? Icons.visibility : Icons
.visibility_off, color: Colors.red,),
),
),
),
Show/Hide Passwords in Flutter's TextFormField
Step 1:
bool _obscureText = true;
Step 2:
void _toggle() {
setState(() {
_obscureText = !_obscureText;
});
}
Step 3:
TextField(
controller: password,
style: TextStyle(fontSize: 16.0),
obscureText: _obscureText,
decoration: new InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: "Password",
suffixIcon: InkWell(
onTap: _toggle,
child: Icon(
_obscureText
? FontAwesomeIcons.eye
: FontAwesomeIcons.eyeSlash,
size: 15.0,
color: Colors.black,
),
),
),
),
Thanks #ShyjuM and # diegoveloper! I see what I was doing wrong - I was calling the buildTextFormField in the constructor of my State class and not in the build method. Moving the call to buildTextFormField inside the build method fixed it. Thanks again for all of your help!
You have some errors in your code.
Replace this :
_passwordVisible > Icons.visibility : Icons.visibility_off,
and
_passwordVisible ^= true;
By this:
_passwordVisible ? Icons.visibility : Icons.visibility_off,
and
_passwordVisible = !_passwordVisible;
This is the Password dart i use
import 'package:flutter/material.dart';
class LoginPass extends StatefulWidget {
LoginPass(this.controllerUpass);
final Function controllerUpass;
#override
_LoginPassState createState() => _LoginPassState();
}
class _LoginPassState extends State<LoginPass> {
bool _isHidden = true;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 10),
child: Container(
height: 35,
child: Center(
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: TextField(
obscureText: _isHidden,
onChanged: (value) {
widget.controllerUpass(value);
},
decoration: InputDecoration(
hintText: 'Password',
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_isHidden = !_isHidden;
});
},
child: _isHidden
? Icon(
Icons.remove_red_eye_sharp,
color: Colors.blue,
)
: Icon(
Icons.remove_red_eye,
color: Colors.red,
),
)),
),
),
),
decoration: BoxDecoration(
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black26,
spreadRadius: 1,
blurRadius: 3,
offset: Offset(0, 3),
),
],
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(3)),
),
),
);
}
}
In Main call
LoginPass(controllerUpass),