Flutter : onSaved event not fired after selected item in MultiSelect - flutter

I am using Flutter Multiselect from official - flutter_multiselect: ^0.5.1
everything works fine , but onSaved() event not fired after selecting/deselecting and clicking the save button in MultiSelect Widget. i just wanna print the selected/deselected item in console.
Note : am also trying to get via change() event , its works only if we selecting the option, not works while deselcting.
help me to resolve this problem
Sample Code:
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
),
alignment: Alignment.center,
child: new MultiSelect(
maxLength: 1,
maxLengthText: "",
autovalidate: false,
dataSource: countries,
textField: 'country_name',
valueField: 'country_id',
hintText: "Select Your Country",
initialValue: countryID,
value: countryID,
required: true,
validator: (value) {
if (value == null) {
return 'Please Select Country';
}
},
filterable: true,
change: (values) {
if (values != null) {
setState(() {
countryID = values.cast<String>();
getStatesByCountry();
});
}
//this event emitted while selecting option from multiselect
//not works on deselecting option from multiselect
},
onSaved: (value) {
debugPrint("on save event");
print(value);
//always not emitting
},
),
)

Since I cannot see whole code, it's hard to tell but I would guess you don't save the whole form like this:
void _onFormSaved() {
final FormState form = _formKey.currentState;
form.save();
}
I would recommend to follow this original example
Hope it somehow help. Cheers

i dont know its a correct way, but in my case just cleaned a build and reinstalled packge will emit onchange event while removing items in multiselect,nothing else works me

Related

I want to validate the user input in flutter

I'm trying to validate different user inputs, and i want to inform them which input is null
i tried to show an alert dialog whenever the user hit the submit button while an input is null, but then i got an error and it didn't open the page saying i have to fill the information before i even open the page. However i tried a something else but unfortunately it didn't work ether this is what i did.
TextFormField(
key: _formKey,
validator: (value) {
if (value == null) {
return 'please write a review';
} else if (DATA == null) {
return 'please select a category';
} else if (image == null) {
return 'please add an image';
} else if (tag == null) {
return 'please select sub category';
} else if (_descriptionController.text == null) {
return 'please select a location';
} else
return null;
},
maxLines: 20,
maxLength: 200,
controller: _descriptionController2,
decoration: InputDecoration(
contentPadding:
EdgeInsets.only(left: 10.0, top: 16.0),
hintText: "What do you think about the place?",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16.0)),
),
),
That's what i added to the button when it's pressed
onPressed: () {
bool valid = validation();
if (valid)
addData(image!, DATA!, lat, lng, _descriptionController2.text,
tag!, loggedInUser2!);
Navigator.pop(context);
},
lastly this is the validation method
bool validation() {
final form = _formKey.currentState;
if (form!.validate()) {
return true;
}
return false;
}
can any one help?
The validator(String? value) in widget TextFormField should validate ONLY for its text value. Other fields like Data, image... should be handled in another place.
I'm also working on validator for TextFormField and I realize that we shouldn't check null. Because when you first time navigate to this screen, the TextFormField will immediately show red error message below and it could make user uncomfortable. You should check null only when user press "Save/Comment" button and show popup/snack bar if the text is null/empty.
Also I got some tricks that you may interest:
Use extension (extension for String?) if you has some special cases can be used in future, like: valid email, valid password (8 character, special symbols)...
Don't forget to use function .trim() to remove white space on textEditingController.
i think is unnecessary for doing validation of DATA,image, etc for description field.
TextFormField will return String, it will always false when you do validation for DATA, image, etc.
just do like this:
Form(
key:_formKey,
child: Column(
children:[
TextFormField(
validator: (String? value) {
// runType value is String?
// which is it always false when you compare to image, or Data.
if (value == null) {
return 'please write a description';
else
return null;
},
controller: _descriptionController2,
),
then if you want to do validation for other data, i think you can make it manually.
if (DATA== null) {
//do something
}
...etc

Flutter dropdown stopped showing selected value

I have a stateful class with this function:
recordSelectedTime(DateTime? selectedTime){
if (selectedTime!=null && kDebugMode) print('Received time: ${DateFormat('hh:mm a').format(selectedTime)}');
setState(() {
time = selectedTime?? DateTime.now(); **// THIS UPDATES TIME**
});
if (selectedTime == null) {
Provider.of<CP>(context, listen: false).getOrder().prefTime = null;
} else {
Provider.of<CP>(context, listen: false).getOrder().prefTime = selectedTime.millisecondsSinceEpoch;
}
}
In my class, I then create a stateless widget and pass this function as a callback function:
TimeSelection(mode: Provider.of<CP>(context).getDeliveryMode(), callBack:recordSelectedTime , def: time,),
Then in my stateless widget there is a dropdown button as below, this used to work before, as in when new value is selected it shows the new value, but then it has stopped working for some reason (flutter upgrade may be?). Now when I select the new value from the dropdown, I have the old same value displayed even after the selection. Although I have confirmed that my callback is working fine with debug statements. Any idea as to what has changed? thanks
child: DropdownButton(
isExpanded: true,
dropdownColor: Colors.white,
items: options,
hint: def.difference(DateTime.now()).inMinutes<3? Text('ASAP (As soon as possible)', style: TextStyle(color: Colors.green),) : Text(DateFormat('hh:mm a').format(def), style: TextStyle(color: Colors.green)),
onChanged: (value) => callBack(value as DateTime),
),

Flutter- TextEditingController listener get called multiple time for textfield

TextField controlled controller.addListener(() gets called multiple time after pressing the clear button, this will only happen if we are clearing it.
Snippet:
TextEditingController controller = new TextEditingController();
TextField field = new TextField(
controller: controller,
autofocus: true,
);
controller.addListener(() {
print("Pressed cancel button");
});
Video Link
Note: While adding characters in TextField listener method gets called only ones.
I guess that would be a defect on flutter, a possible solution would be to use onChanged()
TextField field = new TextField(
autofocus: true,
onChanged: (String value) {
print("Pressed clear button");
},
);
I have the same problem with Nexus 6p when used with API level 23 and Pixel with API 25.
but this problem did not occurs with Pixel with API28 and it does not occurs with Nexus6P with API26.
exact code from https://flutter.dev/docs/cookbook/forms/text-field-changes was used.
1. We need to create our own .clear() method
void clearField() {
print("c: clearField");
var newValue = textController.value.copyWith(
text: '',
selection: TextSelection.collapsed(offset: 0),
);
textController.value = newValue;
callApi('');
}
// and call it by :
child: TextField(
controller: textController,
autofocus: true,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(Icons.close),
onPressed: clearField, // call
),
),
),
2. We need to carefully handle changes
void changesOnField() {
print("c: changesOnField");
String text = textController.text;
if (text.isNotEmpty) { // set this
callApi(text);
}
}
Full Code
You may look into this repo and build it locally Github
Result

Add text to TextField from an outside source

I added a speech recognition to a text field, it works but I cannot manage to add the text to the textfield, is there a way to do that.
the textfield looks like this:
Widget _buildDescriptionTextField(productBloc) {
return StreamBuilder<Object>(
stream: productBloc.messageStream,
builder: (context, snapshot) {
return TextField(
maxLines: 3,
controller: _controllerMessage,
onChanged: productBloc.messageSink,
decoration: InputDecoration(
labelText: allTranslations.text(StringConstant.description),
errorText: snapshot.error,
suffixIcon: IconButton(icon: Icon(Icons.mic), onPressed: () {
if (_isAvailable && !_isListening)
_speechRecognition
.listen(locale: "en_US")
.then((result) => print('$result'));
},
),
),
);
}
);
}
I have a steam-builder to manage the added text manually, and an controller if this page is used for editing, then as suffixsIcon the iconButton to start the speech recognition. when I add the result text outside a text Widget it works but I need it inside the texField.
Just doing that should work no ?
setState(() => _controllerMessage.text = result)
You need to use TextEditingController properties. I assume you declared one as _controllerMessage.
To set new value to your TextField and keep the cursor in the end - use something similar to the example from the Docs.
e.g.
_speechRecognition
.listen(locale: "en_US")
.then(_onResult);
// ...
void _onResult(String result) {
setState(() {
_controllerMessage.value = _controllerMessage.value.copyWith(
text: result,
selection: TextSelection(baseOffset: result.length, extentOffset: result.length),
composing: TextRange.empty,
);
});
}
Let me know if this helped.
So What I did is just used the _speechRecognition.setRecognitionResultHandler from the documentation, to set a new value to the controller of the textField, like so:
_speechRecognition.setRecognitionResultHandler(
(String speech) => setState(() {
_controllerMessage = new TextEditingController(text: resultText = speech);
})
);
the textField stays like it was before, see question.

Detect 'enter key' press in flutter

In my case i need to scan barcode and fetch product details. Normally barcode scanner devices emit enter key(keycode=13) event at end of scanning, But in flutter enter key is not same as Done so how can code to detect enter key pressed in my TextFormField widget?
if you are using TextField then you have to add onSubmitted in your text field to detect when user press Enter key. For my case, I changed Done in keyboard to TextInputAction.Search. It also works for TextInputAction.Done too. here is a sample code
TextField(
onSubmitted: (value){
//value is entered text after ENTER press
//you can also call any function here or make setState() to assign value to other variable
},
textInputAction: TextInputAction.search,
)
The solution above works, but I believe RawKeyboardListener is a more reliable and flexible solution. You just need to cover the text field with it and start to listen to keyboard events:
var focusNode = FocusNode();
RawKeyboardListener(
focusNode: focusNode,
onKey: (event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
// Do something
}
},
child: TextField(controller: TextEditingController())
)
As a second option you can use onKey method of the FocusNoded and pass the node to your text field:
var focusNode = FocusNode(onKey: (node, event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
// Do something
// Next 2 line needed If you don't want to update the text field with new line.
// node.unfocus();
// return true;
}
return false;
});
TextField(focusNode: focusNode, controller: TextEditingController())
In case someone is looking for the same solution (as Al Walid Ashik) but for TextFormField, just use the following:
TextFormField(
/// ...
onFieldSubmitted: (value) {
/// do some stuff here
},
),
TextFormField(
maxLines: null,
autovalidate: true,
validator: (value){
if(value.contains('\n')){
doFun(value);
}
}
)
When user press enter key new line create in text box. We check with that.
maxLine:null - to hide multiline
autovalidate:true -to automatically run validator fun
'\n' - new line ('\s'-whitespace,'\t'-tab.. etc)
In addition to the Sergey Yamshchikov's answer:
In case if it is a multiline TextField (maxLines: null) and you want to catch up the entered key and prevent passing it into the text field, you can use this approach:
RawKeyboardListener(
focusNode: FocusNode(onKey: (node, event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
return KeyEventResult.handled; // prevent passing the event into the TextField
}
return KeyEventResult.ignored; // pass the event to the TextField
}),
onKey: (event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
// Do something
}
},
child: TextField(controller: TextEditingController())
)
But, if you need to detect the keys combination, like ctrl+enter, then you can use CallbackShortcuts:
CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.enter, control: true): _doSomething(),
},
child: Focus(
autofocus: true,
child: TextField(controller: TextEditingController()),
),
);