I have created a form using scrollview widget & when initState() method _getDataUser() is called i set some prefill controllerEmail.text to textfield which makes my scrollview to scroll to the TextFormField Email source code :
https://pastebin(dot)com/sFR7s4wS
I found a solution here, you can wrap your TextField into a Focus, and only when the user has focused on the text field we set showCursor to true.
bool showCursor = false;
Focus(
onFocusChange: (focus) => setState(() => showCursor = focus),
child: TextField(
showCursor: showCursor,
controller: _textController,
textCapitalization: TextCapitalization.words,
),
)
This is flutter's native functionality and I have programatically solved this using ScrollController and Future.delayed. Just assign your scroll view or list view to a scroll controller and do the following:
runZoned(() {
Future.delayed(Duration(seconds: 0), () {
_scrollController.jumpTo(0);
});
}, onError: (error, stackTrace) {
print('Zone Error: $error');
});
Related
Use case: Messaging app you edit your message: keyboard, blinking cursor and initial text appears but pointer (cursor) is not
But on Flutter when you use initial text (or via textController) there are always pointer(cursor) which is not wanted
Example
Steps to reproduce:
run flutter create bug
edit main.dart to replace center text (line 100) to MyStatefulPage(),
class MyStatefulPage extends StatefulWidget {
#override
State<MyStatefulPage> createState() {
return _MyStatefulPageState();
}
}
class _MyStatefulPageState extends State<MyStatefulPage> {
TextEditingController controller;
#override
void initState() {
super.initState();
controller = new TextEditingController();
controller.text = 'My Initial Text';
}
#override
Widget build(BuildContext context) {
return TextField(
decoration: InputDecoration(
border: InputBorder.none
),
// showCursor: false,
controller: controller,
autofocus: true,
maxLines: 8,
);
}
}
With that code when you open app keyboard will appear but so will pointer(cursor) I want to hide this cursor(pointer).
Note: it's only for Android.
TextField set enableInteractiveSelection property to false can resolve this issue
TextFormField cursorHeight: 0 and cursorWidth: 0 can hide the cursor.
in textformfield use showCursor: false
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
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.
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()),
),
);
I have a text field value powered by a State variable with some calculation, I want to live calculate and update the same state variable back when user inputs value. The final result just doesnt work, text fiend input behaves strangely.
If I use onSubmitted instead of onChanged, it works well, I guess I am not in a loop of updating values back and forth from the state variable.
Any idea how can I make this happen?
myController.text = '${value.toStringAsFixed(1)}';
TextField(
onChanged: (text){
this.onValueChange(text, index);
},
controller: myController,
),
and the function onValueChange is calling to set state is this
void setValue(_value, _index){
setState((){
value =double.parse(_value)/exchangeRate["rates"][currencies[_index]];
});
}
Suppose we want to make a textfieild for OTP and submit button press once on that it display the OTP on console screen and we fill that our text field same as console
add listener to get the text field value
void initState() {
super.initState();
// update value in listener
myController.addListener(() {
setState(() {
myController.text = "your value";
});
});
}
// your textField
TextField(
controller: myController,
),
You need to use setState inside onChanged
TextField(
onChanged: (text){
setState(() {
this.onValueChange(text, index);
});
},
controller: myController,
),