Flutter save text in textfielf - flutter

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

Related

How to save DropdownButtonFormField value to Firebase real-time database?

I'm using firebase real-time database and I have a form where the user adds the information to the database using it, but I'm stuck with the DropdownButtonFormField, how can I store the value in my database when the form button is pressed?
I used to use the controller when it was TextFormField, but now, I don't know what to do
DropdownButtonFormField(
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(20.0)),
borderSide:
BorderSide(width: 2, color: appColor),
),
labelText: 'Location',
labelStyle: TextStyle(
fontSize: 20, color: Colors.black)),
isExpanded: true,
// Initial Value
value: selectedLocation,
icon: const Icon(
Icons.keyboard_arrow_down,
color: appColor,
),
// Array list of items
items: Locations.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
// After selecting the desired option,it will
// change button value to selected value
onChanged: (String? newLocation) {
setState(() {
selectedLocation = newLocation!;
});
},
),
you get the selectedLocation value and pass that to firebase method. print selectedLocation in the onChange method then when ever you click item in dropdown, the selectedLocation will change.
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
await ref.set({
"selectedLocation": selectedLocation ,
});

Show hint text in text field even if text field contains only spaces

How can I display a hint text in a TextField if it contains only space characters like ' '?
const TextField(
decoration: InputDecoration(
hintText: 'a hint text'
),
),
In this code example the hint text is only displayed if the content of the TextField is empty.
I need this because I need to detect when the user press the backspace button on an empty TextField. Read more here: https://medium.com/super-declarative/why-you-cant-detect-a-delete-action-in-an-empty-flutter-text-field-3cf53e47b631
After diving deeper into the problem I found a solution with InputDecorator:
const InputDecorator(
isEmpty: true, // if true, the hint text is shown
decoration: InputDecoration(
hintText: 'a hint text'
),
child: TextField(),
),
So my solution is this:
String _value = ''; // state variable
...
InputDecorator(
isEmpty: _value.trim().isEmpty, // override the default isEmpty behavior
decoration: const InputDecoration(
hintText: 'a hint text',
),
child: TextField(
onChanged: (v) => setState(() => _value = v),
),
),
Probably, you should use decoration property of your TextField.
Something like that:
SizedBox(
height: 50,
width: 100,
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
label: Text('Your stable hint')
),
)
),

Resetting TextfieldController for all textfields, using provider

I'm having a problem trying to figuring out the proper way on how to do this. Basically in my app, I want to reset all the fields for "cleanup" by the user. I can reset everything, but the TextFields. The only way that I found to solve the problem is by using the if that you can see inside the Consumer. I don't think though it's the proper way on how to handle this type of thing.
I also thought to push inside my provider class all the controller and then reset them, but I think it's still too heavy. I'm trying to find the cleanest and lightest solution, even to learn what's the best practice in these situations.
Thanks in advance!
return Provider.of<Provider_Class>(context, listen: false).fields[_label] != null ? SizedBox(
height: 57.5,
child: Consumer<Provider_Class>(builder: (context, provider, child) {
if (provider.resetted == true) {
_controller.text = "";
}
return Material(
elevation: this.elev,
shadowColor: Colors.black,
borderRadius: new BorderRadius.circular(15),
animationDuration: new Duration(milliseconds: 500),
child: new TextField(
focusNode: _focusNode,
keyboardAppearance: Brightness.light,
style: Theme.of(context).textTheme.headline5,
controller: _controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.end,
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(8),
_whichLabel(widget.label),
],
decoration: new InputDecoration(
enabledBorder: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(15),
borderSide: new BorderSide(width: 1.2, color: CliniLiliac300),
),
focusedBorder: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(15),
borderSide: new BorderSide(width: 2.5, color: CliniLiliac300),
),
filled: true,
fillColor: Colors.white,
hintText: "0.0",
hintStyle: new TextStyle(fontSize: 15, color: Colors.black, fontFamily: "Montserrat"),
),
onChanged: (val) {
var cursorPos = _controller.selection;
val = val.replaceAll(",", ".");
if (val == "") {
provider.fields[_label] = 0.0;
} else if (double.parse(val) > provider.measure[_label] &&
provider.measure[_label] != 0) {
provider.fields[_label] % 1 == 0
? _controller.text = provider.fields[_label].toString().split(".")[0]
: _controller.text = provider.fields[_label].toString();
if (cursorPos.start > _controller.text.length) {
cursorPos = new TextSelection.fromPosition(
new TextPosition(offset: _controller.text.length),
);
}
_controller.selection = cursorPos;
} else {
provider.fields[_label] = double.parse(val);
}
provider.calculateResultRA();
},
),
);
}),
) : SizedBox();
}
Use TextFormField instead of TextField. TextFormField has several callbacks like validator, onSaved, onChanged, onEditingComplete, onSubmitted, ...
You can connect all your TextFormFields by wrapping it in a Form. This form should be given a GlobalKey so that you can identify the Form and call methods on FormState.
final _form = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
// ...
return Form(
key: _form,
child: // build Material with TextFormFields
);
}
Now to call onSaved on each TextFormField, you can call _form.currentState().save(). To reset every TextFormField you can call _form.currentState().reset().
You can get more information about how to build a Form and the functions you can call on FomState here:
https://flutter.dev/docs/cookbook/forms/validation
https://api.flutter.dev/flutter/widgets/FormState-class.html

How to update keyboardType in Flutter (in the app)?

In normal Android development, you can change the keyboard type dynamically but I can't seem to find a way to do so in Flutter.
TextInputType roomKeyboardType = TextInputType.text; // right on top of the build function
My custom form field:
Padding(
padding: const EdgeInsets.all(8.0),
child: FormBuilderTextField(
attribute: "room",
controller: widget.controllers[1],
keyboardType: roomKeyboardType,
decoration: InputDecoration(
filled: true,
labelText: "Room",
prefixIcon: Icon(Icons.location_on, color: Colors.black),
suffixIcon: IconButton(
icon: Icon(Icons.keyboard, color: Colors.black),
onPressed: () {
if (roomKeyboardType == TextInputType.text) {
roomKeyboardType = TextInputType.number;
return;
}
roomKeyboardType = TextInputType.text;
},
)),
validators: [
FormBuilderValidators.required(
errorText: "Please enter the room number",
),
],
),
),
Right now, I have something that looks like this with a keyboard IconButton on the end of the form field. When I click on it, I expect my keyboard type to change, yet when I do, nothing happens. It's supposed to toggle between text and number keyboard types and it only stays on text as that's what I have the variable initially set to. The variable I know is changing, it's just the fact that Flutter probably isn't remaking the widget so the keyboard stays the same. Is there any way to get around this and am I able to change the keyboardType dynamically?
you can change your keyboard type in TextFieldWidgets and many input widgets
like this:
TextField(
keyboardType: TextInputType.number,
hintText: '6 Digit-Code',
),

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