Flutter TextField onFieldSubmitted, how does it work? - android

I have this BMI Calculator and I want that the Height can not be under 100 (cm). For that I created a TextFormField which looks like the following:
TextFormField(
onFieldSubmitted: (value) {
setState((){
_heighController.text= value;
if (int.parse(value) >= 100) {
value = "100";
}
value=_heighController.text;
});
},
inputFormatters: [
LengthLimitingTextInputFormatter(3),
FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*')),
],
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
style: const TextStyle(fontSize: 16, color: Colors.white),
controller: _heighController,
cursorColor: Colors.white,
decoration: InputDecoration(hintText: "in cm", hintStyle: TextStyle(color: Colors.white)),
),
as you can see, I already tried to add onFieldSubmitted, but this doesn't work out like I planned. When I write 90 e.g., it accepts 90 when I press the "enter" button on my keyboard. But when I update the state for this widget with my Plus or minus button (see picture below) it goes to 100 automatically. I want that it goes to 100 every time I leave the "editing option" from this field and the input is below 100. How do I realize that?

You should change the value of the _heighController on your "onFieldSubmitted" function, like this:
onFieldSubmitted: (value) {
setState((){
if (int.parse(value) <= 100) {
value = "100";
}
_heighController.text= value;
});
},
Your error was to attribute the value to your controller before checking the validity.
And after, you set the value of your controller to the parameter of the function, which is pointless in this case.

Related

Button Text Initialization in flutter with SwitchListTile

I have a SwitchListTile in my App that determine the text that should be written on another button based on its value. Everything is working fine except for one thing which is that the first time you open the app, the initial text on the button will be nothing '' just as it was declared first time until I switch the SwitchListTile for the first time. So I want to know how to make the text appear from the moment you enter this page.
This is my code:
static String buttonText='';
SwitchListTile(
title: const Text('Enable Bluetooth'),
value: _bluetoothState.isEnabled,
onChanged: (bool value) {
// Do the request and update with the true value then
future() async {
// async lambda seems to not working
if (value) {
await FlutterBluetoothSerial.instance.requestEnable();
setState(() {buttonText = "Press to start collection" ; });
} else {
await FlutterBluetoothSerial.instance.requestDisable();
setState(() {buttonText = "Please enable bluetooth in your device" ; });
}
}
future().then((_) {
setState(() {});
});
},
),
.......................
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
padding: const EdgeInsets.symmetric(horizontal: 30, vertical:40),
textStyle:
const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
onPressed: () {
if(_bluetoothState.isEnabled){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BluetoothConnectionTask()),
);
}
},
child: Text(
buttonText,
style: TextStyle(fontSize: 28,color: Colors.black, letterSpacing: 2.0),
),
),
Please update the Text widget set in your elevated button as below.
Text(
_bluetoothState.isEnabled ? "Press to start collection" : "Please enable bluetooth in your device",
style: TextStyle(fontSize: 28,color: Colors.black, letterSpacing: 2.0),
)
And remove
setState(() {buttonText = "Press to start collection" ; });
setState(() {buttonText = "Please enable bluetooth in your device" ; });
from the onChanged method.
It is not working from first time because, onChanged method will get call when you interact with the SwitchListTile.
If still it's not working, Please let me know with the issue.

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.

Add a prefix to every line in a multiline Text Input in Flutter?

I wanted to know if there was a way of adding a prefix (like "- ") to every line in a multiline Text Input in Flutter.
For example:
Hello
World!
Would become:
-Hello
-World!
This is my code:
TextField(
maxLines: null,
controller: _elementsController,
textCapitalization: TextCapitalization.sentences,
style: TextStyle(
fontSize: 18.0,
),
decoration: InputDecoration(
contentPadding: EdgeInsets.all(0.0),
labelText: 'Elements',
),
),
U can add a - everytime a new line is created.
Add this in your initState(),
final prefix = '-';
_elementsContoller.addListener(() {
if(_elementsController.text.endsWith('\n')) {
// Add the prefix everytime a new line is created
_elementsController.text += prefix;
}
}
If these changes should be made after the input,
text.replaceAll('\n', '\n$prefix');

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

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