Flutter error Method "contains" can't be unconditionally - android

I havea bug where my code cant be build because this errorr
can someone look my code
here the code
Text(
"Login",
style: Theme.of(context).textTheme.headline2,
),
SizedBox(height: 20,),
new TextFormField(
keyboardType: TextInputType.emailAddress,
validator: (input) => !input.contains("#")
? "Email id Should be Valid"
: null,
)
],
),
),
),
it show error message "The method 'contains' can't be unconditionally invoked because the receiver can be 'null' try making the call conditional (using '?.' or adding a null check to target
can someone please fix my bug
thanks before

You need to use:
TextFormField(
keyboardType: TextInputType.emailAddress,
validator: (input) => !(input?.contains("#") ?? false)
? "Email id Should be Valid"
: null,
)
As per the official documentation FormFieldValidator, the validator parameter is an optional String. So you need to convert that to non-nullable String first.

Related

Allow spaces in EMail validator in flutter

Im using email validator package on flutter to validate the email for login. I have one issue with this package that I want to allow spaces in the email when the user sign in because Im gonna trim the text anyway so I dont want it to show error when there is Spaces at the end.
child: TextFormField(
keyboardType: TextInputType.emailAddress,
controller: emailController,
cursorColor: Colors.white,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Email'),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (email) =>
email != null && !EmailValidator.validate(email)
? 'Enter a valid Email' : null,
try {
await _auth.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
Anyone knows how to do it or if there is a better way than using this package?
You don't need to use any package for validating email you can simply do it with RegExp like below in this space is allows and then you can trim it where ever you want to use
validator: (value) {
bool emailValid = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(value!);
if (value == null || value.isEmpty) {
return 'Please Enter Email Address';
}else if (emailValid == false){
return 'Please Enter Valid Email Address';
}
return null;
},
Let me know if you have any questions. Thanks
You can trim email first then you can check for validation.
validator: (email) {
if(email != null) {
email = email.trim();
(!EmailValidator.validate(email))
? 'Enter a valid Email' : null,
}
return null;
}
best practice to use TextFormField validation is to not to allow user to put irrelevant data
TextFormField(
controller: _etcEmail,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.done,
inputFormatter: [
// FilteringTextInputFormatter.allow(RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")),
// FilteringTextInputFormatter.deny(RegExp(r" ")),
FilteringTextInputFormatter.allow(RegExp(r" ")),
],
hintText: 'Email',
validator: (value) {
if (value!.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.pinkAccent,
behavior: SnackBarBehavior.floating,
padding: EdgeInsets.all(5),
content: (Text('Email Field is Required'))));
}
},
read: false,
)

I want to make TextField required for the user

I just want to make my TextField as required field, in which I am using Email and password to login for the user. Please let me know how can I make it required and if user don't fill it, how can I give him warning.
TextField (
onChanged: (value) {
email=value;
},
style: const TextStyle(color: Colors.black),
decoration: InputDecoration(
fillColor: Colors.grey.shade100,
filled: true,
hintText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
),
),
const SizedBox(
height: 30,
),
TextField(
onChanged: (value) {
password=value;
},
style: const TextStyle(),
obscureText: true,
decoration: InputDecoration(
fillColor: Colors.grey.shade100,
filled: true,
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
),
),
The esiest way to set a validation logic for the TextField in Flutter is to use TextFormField instead of TextField in combination with Form widget.
It provides you with a callback called validator which is called whenever you call .validate() method in the Form Key.
To learn more about using Form widget in Flutter along with TextFormFiled and validation, check out this video.
Example for a condition in the validator to make the field required:
validator: (String? value) {
if (value == null)
{
return 'This field is required';
}
return null;
},
NOTE:
If the validator callback returned a message, this means the message would be displayed in the errorText for the TextFormField and the .validate() method would return false.
If the validator callback returned null, this means that no errors and the .validate() method would return true.
if user click on submit button then you can check for is email or password field is empty or not empty.

How to implement autosave in flutter textfield similliraly like in major ides on desktop?

How to can I implement a callback that fires after every few seconds or when user stop typing in TextField ?
Or is it performant to just implement in onChanged callback directly ?
input Field onChanged gives the input value when ever user types in, So you may use onChnaged callback function to save the input, like below,
TextFormField(
controller: _nameController,
onChanged: (value) {
saveData();
},
initialValue: widget.user.userName,
onSaved: (val) {
widget.user.userName = val;
},
validator: (val) =>
val.length > 3 ? null : 'Full name is invalid',
decoration: InputDecoration(
labelText: 'Full Name',
hintText: 'Enter your full name',
icon: Icon(Icons.person),
isDense: true,
),
),

How to make flutter SimpleAutoCompleteField suggest based on contains not startWith

I've used SimpleAutoCompleteTextField in my flutter project but am facing a problem of not being suggestions the right suggestions unless I started to type the beginning of the word not from the middle of it .. example:
When I am looking for the word "Astalavista", if I type "asta" it will be suggested but if I typed "lavis" it won't be suggested, I need to fix this out.
Here is my code :
child: SimpleAutoCompleteTextField(
key: endKey,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: S.of(context).end_location_hint),
controller: endLocationTextEditingController,
suggestions: suggestions,
textChanged: (text) => currentText = text,
clearOnSubmit: true,
textSubmitted: (text) async {
await movingCameraToLocation(
double.parse(
allStations[suggestions.indexOf(text)]
.stationLatitude),
double.parse(
allStations[suggestions.indexOf(text)]
.stationLongitude));
toLocationName = text;
setState(() {});
},
),
Try adding the filter parameter, im not sure if it can be used with SimpleAutoCompleteTextField, but the official documentation states that
"itemFilter" parameter can be used with AutoCompleteTextField <String>(),
Your filter would be :
itemFilter: (suggestion, input) =>
suggestion.toLowerCase().contains(input.toLowerCase()),```

TextFormField overlapped with keypad For Flutter added in existing android app

I am added text field in a flutter, but the keypad is overlapping with a text field when we added this in Flutter as view in the existing android app. if the same code runs independently as only Flutter application it will work.
TextFormField(
focusNode: payTMFocus,
controller: payTMController,
inputFormatters: [
LengthLimitingTextInputFormatter(10),
WhitelistingTextInputFormatter.digitsOnly,
],
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: "Enter mobile number",
filled: true,
hintStyle: getTextStyle(),
hasFloatingPlaceholder: true),
},
validator: (value) {
if (value.length != 10) {
return "Enter valid mobile number";
} else {
return null;
}
},
)
tried seting true to resizeToAvoidBottomPadding for root Scaffold
Github issue link -https://github.com/flutter/flutter/issues/47107
By overlapping means i guess you are not able to see textField as keypad shows over it.
If this is the case then you can use SingleChildScrollView to give scrollable view to area in which your text field is.
child:SingleChildScrollview(
...//container or column or some other widgets you have above in hierarchy
child:TextFormField(
focusNode: payTMFocus,
controller: payTMController,
inputFormatters: [
LengthLimitingTextInputFormatter(10),
WhitelistingTextInputFormatter.digitsOnly,
],
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: "Enter mobile number",
filled: true,
hintStyle: getTextStyle(),
hasFloatingPlaceholder: true),
},
validator: (value) {
if (value.length != 10) {
return "Enter valid mobile number";
} else {
return null;
}
},
)
),
Hope this helps ! please comment if you are expecting some another solution.
happy to help :)

Categories

Resources