Updating a text widget using onchanged - flutter

I am trying to update a text widget as the user types, its working but i don't see the input as I type
TextFormField(
autofocus: true,
controller: amountController,
keyboardType: TextInputType.number,
cursorColor: Colors.amber,
decoration: InputDecoration(
hintText: "Enter Amount",
prefixIcon: Material(
elevation: 0,
borderRadius: BorderRadius.all(Radius.circular(30)),
child: Icon(
Icons.phone_outlined,
size: 15,
color: Color(0xff020529),
),
),
border: InputBorder.none,
contentPadding:
EdgeInsets.symmetric(horizontal: 25, vertical: 13)),
onChanged: (value) {
add(value);
},
),
this is the widget
Text( x.toString(),
style: TextStyle(fontWeight: FontWeight.bold),
),
This is my method
add(String value) {
var ans = 36 * double.parse(value);
print('ddd');
setState(() {
x = ans;
});

What's happening is double.parse is failing because the given value can't be converted to a number.
One option to handle this is by using a try catch (see following code sample), and then setting the displayed value to 0 (or could also do something like set an error message saying something like "invalid input" if the user enters something like "123d"
add(String value) {
double ans;
try {
ans = 36 * double.parse(value);
} on FormatException catch (e) {
// string couldn't be formatted to double
ans = 0;
}
setState(() {
x = ans;
});
}
I used a try catch, but you could also check if value is empty, and/or add an onError callback to double.parse.

Related

When tap on textfield, app crashes returns homepage

Hi I get an error when user focus textfield, app crashes and returns to homepage (see clip here https://www.screencast.com/t/yiJkCBsibcoY)
I've had this error for a while now and cannot seem to fix it, sometimes it happens on other textfields. I cannot replicate the issue only sent from users. Anyone experience this with flutter?
Widget searchBox() {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
border: Border.all(color: Color(0xff0F004E), width: 1.0),
),
child: SimpleAutoCompleteTextField(
key: keyAuto,
controller: textController,
suggestions: suggestions,
textChanged: (text) => searchProduct = text,
textSubmitted: (text) {
loadingBarActive = true;
_sendAnalyticsEvent(text, 'serach_food_action');
searchProduct = text.replaceAll(new RegExp(r'[^\w\s]+'), '');
print('searchProduct RegX $searchProduct');
newSearch = true;
_filterCategories(searchProduct);
_filterRecipes(searchProduct);
// reset search values to intial
usdaItems.clear();
usda!.clear();
perPage = perPageIntial;
present.value = 0;
loadingBarActive = false;
selectApi = <int, Widget>{
0: allProductTab(),
1: allProductTab(),
2: allProductTab(),
3: allProductTab(),
};
setState(() {
_loadUSDAlist = usdaFoodProductList();
_loadOpenList = openFoodProductList();
});
},
style: TextStyle(
fontFamily: 'Nunito', fontSize: 20.0, color: Color(0xff0F004E)),
decoration: InputDecoration(
border: InputBorder.none,
// contentPadding: EdgeInsets.only(top: 14.0),
hintText: 'Search',
hintStyle: TextStyle(
fontFamily: 'Nunito', fontSize: 16.0, color: Color(0xff0F004E)),
prefixIcon: Icon(Icons.search, color: Color(0xff0F004E)),
suffixIcon: IconButton(
icon: Icon(Icons.close, color: Color(0xff0F004E)),
onPressed: () {
textController.clear();
})),
),
);
}
I had exactly the same issue and was literally going crazy trying to find the solution. For me the error originated in my usage of the GetX state management library. For me the issue was solved by replacing this:
Get.to(ReservationDetails(res: Reservation.empty()))
?.then(((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
})));
with:
Navigator.push(context,
MaterialPageRoute(
builder: ((context) =>
ReservationDetails(res: Reservation.empty()))))
.then((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
}));
I suggest you have a look at how you are opening the page you are experiencing this issue.

flutter space between inputTextForm field and bottom border

Everything works fine except the space between the elements/user input and bottom bar. I tried different methods to get rid of that space: content padding, box constraints, prefix icon constraints etc. None worked. Eventually I limited the height of this widget, but then my error message was placed on top of user input and I was getting this message Another exception was thrown: BoxConstraints has a negative minimum height.
Here is the code:
Widget _emailField(FormBloc formBloc) {
return StreamBuilder(
stream: formBloc.email,
builder: (context, AsyncSnapshot<String> snapshot) {
return TextFormField(
autofocus: false,
keyboardType: TextInputType.emailAddress,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null) {
return "Email cannot be empty";
} else {
if (value.isEmpty) {
return "Email cannot be empty";
}
}
},
onChanged: formBloc.changeEmail,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.email,
size: 15,
),
contentPadding: const EdgeInsets.all(0),
labelText: "Email",
labelStyle: const TextStyle(fontSize: 14),
errorText:
snapshot.error != null ? snapshot.error as String : null,
),
);
}
);
}
I need to make everything work as before, except this time I do need to have no space between bottom border and input elements, how can I do so?
First inside InputDecoration(), you can give zero padding to your prefix icon.
Then set prefixIconConstraints to BoxConstraints(maxHeight:0)
Still isn't enough you can give negative value to contentPadding: EdgeInsets.only(bottom:-5),.
InputDecoration(
prefixIcon: Padding(
padding: EdgeInsets.only(right:10),
child:const Icon(
Icons.email,
size: 15,
),
),
prefixIconConstraints: BoxConstraints(maxHeight:0),
contentPadding: EdgeInsets.only(bottom:-5),
labelText: "Email",
labelStyle: const TextStyle(fontSize: 14),
errorText:"error",
)

TextFormField cuts last character input

I'm having a weird issue with a TextFormField, it cuts off the last input. If I type something like hello, it's gonna cut off the o and save hell. if I give it a space like hello , it's gonna save hello. Has anyone been through the same issue and know how to fix it?
here is my code:
String messageText;
_ChatScreenState() {
_formKey = GlobalKey<FormState>();
_scrollController = ScrollController();
messageText = "";
}
Widget messageTextField() {
return SizedBox(
width: deviceWidth * 0.55,
child: TextFormField(
style: TextStyle(color: Colors.white),
validator: (text) {
if (text.isEmpty) {
return 'Digite sua mensagem';
}
return null;
},
onChanged: (text) {
_formKey.currentState.save();
},
onSaved: (text) {
setState(() {
messageText = text;
});
},
cursorColor: Colors.white,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Digite uma mensagem',
hintStyle: TextStyle(color: Colors.white.withAlpha(100))),
autocorrect: false,
),
);
}
I do not think save() is intended to be used with onChanged.
If you place a button somewhere and perform _formKey.currentState.save(); within onPressed of the button, you should see the entire text value being saved.

Flutter save text in textfielf

I am trying to create a kind of forum using text fields. The thing is that when you fill in the blacks and press next and than you go back again, the text field will appear empty as if you have no value in it but its actually saved. I want it so that you can see what you entered inside even if you go forward and than back. I will attach some photos so you can understand better what i mean.
Here is the photo of the text field:
https://gyazo.com/9ceb0ef4f27db1be842cbdfac885fc01
In this photo i fill in the blanks:
https://gyazo.com/6365ab3fcc9d8167a1c9163563fbf3d7
Than i go forward:
https://gyazo.com/8490115e74b57e96cd1f3a9486db5fad
And when i go back again, the text field looks empty but the value is not empty, i want it so that i can still see the value inside:
https://gyazo.com/07eec4c58149641926d7f037bb0f949c
Here i will put the code of the TextFIeld:
Container(
margin: EdgeInsets.only(top: 20),
width: 360,
child:
Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus.context).save();
},
child: TextFormField(
decoration: new InputDecoration(
labelText: "Event Name",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
validator: (val) {
if (val.length == 0) {
return "Event Name cannot be empty";
} else {
return null;
}
},
onSaved: (String value) {
eventname = value;
},
style: new TextStyle(
fontFamily: "Poppins",
))))
add an initial value to your textformfield by loading the saved value

how to save input value of text form field as soon as type completed in flutter

i have a text form field that user enter to it a code that sent to it and i must decide if input code is true or false but can not save value of text form field i have a button like it
GestureDetector(
onTap: () {
_formKey.currentState.save();
setState(() {
inputcode=key.getter("sms");
print(inputcode);
print(verifycode);
});
},
child: inputcode==verifycode?send:
VirtualBotton("please enter correct code","ok",40.0,10.0,width: 120.0,),
)
but i must press two times button for done this work
in this code when i enter correct code first run virtual Button class and second times that i press button run correct code how to run on tap before build child in button this is text form field
TextFormField(
inputFormatters: [
new LengthLimitingTextInputFormatter(30),
],
onSaved: (value) {
key.setter(id, value);
},
textAlign: alignment == null ? TextAlign.right : alignment,
maxLines: maxlines==null?1:maxlines,
style: TextStyle(
fontSize: 14,
),
textDirection: TextDirection.rtl,
controller: ctrl,
validator: (String value) {
if (value.isEmpty) {
return "";
}
return null;
},
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: const EdgeInsets.all(0.0),
hintText: _hint,
errorStyle: TextStyle(height: 0),
hintStyle: TextStyle(
color: hintconlor == null ? Colors.grey : hintconlor,
fontSize: hintsize == null ? 13 : hintsize)),
),
);
you can add TextEditingController and listen to controller changes. Here are docs with examples