TextField with long text, horizontal scroll reset to start - Flutter - flutter

Building a stateful widget with a textfield wrapped within a Container of specific width. Now, when I type a long text in the textfield, the view scrolls right as you type (works as expected). But when I tap outside of the textfield, I've unfocused the textField. When I unfocus, how do I programatically reset the view of the textfield back to the beginning of the text? i.e. Move the horizontal scroll back to the beginning?
Here's the textField widget
textContainer = Container(
width: MediaQuery.of(context).size.width * 0.68,
child: Focus(
child: TextField(
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.sentences,
onSubmitted: onSubmit,
controller: textController,
focusNode: widget.focusNode,
maxLines: 1,
autofocus: widget.isNew,
cursorColor: Colors.white,
style: const TextStyle(
fontSize: 16.0,
fontFamily: 'Inter',
fontWeight: FontWeight.normal,
color: Colors.white
),
decoration: const InputDecoration(
border: InputBorder.none,
),
onChanged: (text) {
Task task = taskBox.get(widget.task.id);
task.text = text;
taskBox.put(widget.task.id, task);
},
),
onFocusChange: (hasFocus) {
showDeleteBtn(hasFocus);
},
)
);
See the mid part of the gif, when I unfocus the textfield, I'd like to push the view/scroll back to the beginning of the widget. Tried rebuild the widget, but doesn't work.

You can use ScrollController inside TextField and while textfiled get unfocused jump to start.
class _TOSState extends State<TOS> {
late final FocusNode textInputFocusNode = FocusNode()
..addListener(() {
debugPrint(textInputFocusNode.hasFocus.toString());
if (!textInputFocusNode.hasFocus) {
controller.jumpTo(0);
}
});
ScrollController controller = ScrollController();
#override
void dispose() {
textInputFocusNode.removeListener(() {});
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus();
},
child: Column(
children: [
TextField(
scrollController: controller,
focusNode: textInputFocusNode,
maxLines: 1,
decoration: const InputDecoration(
hintText: "TYpe",
),
),
],
),
));
}
}

Related

the values not remain in the Text Form Field when I click continue, then when I return to the page the value is empty Note that I used Page View

I'm trying to make Sign Up pages so I used Page View like this
page view controller.nextPage(....,...)
page view controller.prev page(....,...)
Boom Value in the Text Form Field is gone.
And this thing happens on all pages when I move to a new page in the page view and return to the page. The information that the user filled in is gone from the fields and has become empty!
why?
Form(
key: EmailKeys.formKey,
child: Column(
children: [
const Text(
"Create an account, It's free",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16, color: Colors.grey),
),
const SizedBox(
height: 40,
),
TextFormField(
onFieldSubmitted: (val) {
EmailKeys.formKey.currentState!.setState(() {
email = val.trim();
});
EmailKeys.formKey.currentState!.save();
},
textInputAction: TextInputAction.done,
inputFormatters: [LengthLimitingTextInputFormatter(100)],
obscureText: false,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: "Email Address",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
labelStyle: TextStyle(color: Colors.grey[400]),
floatingLabelStyle:
const TextStyle(color: Colors.blueGrey, fontSize: 18),
),
validator: (value) {
if (value!.isEmpty) {
return 'Email address is required';
} else if (!value.contains("#")) {
return "Email address should contain ' # ' symbol";
}
},
onChanged: (value) {
email = value.trimLeft();
},
onSaved: (val) {
setState(() {
email = val!;
});
print(email);
},
controller: _emailCtrl,
),
],
),
),
Use TexEditingController in TextFormField to hold and retrieve data https://api.flutter.dev/flutter/widgets/TextEditingController-class.html
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final TextEditingController _controller = TextEditingController();
#override
void initState() {
super.initState();
_controller.addListener(() {
final String text = _controller.text.toLowerCase();
_controller.value = _controller.value.copyWith(
text: text,
selection:
TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
});
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(6),
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(border: OutlineInputBorder()),
),
),
);
}
}

Flutter:How to automatically clear my TextFields?

I want to recreate automatically my page and clear all my TextFields on button press.Is there a method to do it?
Edited :
Here is an example of how to achieve this :
class _MyWidgetState extends State<MyWidget> {
final myAController = TextEditingController();
final myBController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
myAController.clear();
myBController.clear();
});
},
child: Text(
"Clear text fields",
),
),
TextField(
controller: myAController,
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Enter value A'),
),
TextField(
controller: myBController,
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Enter Value B'),
),
],
),
),
);
}
}
As you can see every time i press my flatbutton the widget reloads with the updated counter value.
Here is an updated working demo.
I think it's
setState((){
// If there is anything you want to change put it here
});
This will rebuild the widget.

How to create TextField with Clear button using TextEditingController?

I tried to create a TextField with clear button, but when i enter some value there's no clear button show up as I wanted to. Seems like it cant detect the changes to the _firstNameController.text. How can I solve this issue?
class TextFieldWithClearBtn extends StatefulWidget {
#override
_TextFieldWithClearBtnState createState() => _TextFieldWithClearBtnState();
}
class _TextFieldWithClearBtnState extends State<TextFieldWithClearBtn> {
final TextEditingController _firstNameController = TextEditingController();
#override
void dispose {
super.dispose();
_firstNameController.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
child: TextFormField(
controller: _firstNameController,
decoration: InputDecoration(
labelText: "First name",
suffixIcon: _firstNameController.text.isNotEmpty
? GestureDetector(
onTap: () {
WidgetsBinding.instance.addPostFrameCallback((_) => _firstNameController.clear());
},
child: Icon(Icons.clear, color: Colors.black38),
)
: null
),
),
);
}
}
Instead of suffixIcon, you suffix. This way the clear button will not be visible if textformfield is not in focus and will display the icon when you tap on the field. Also, when you will tap on the clear icon after typing something, it'll clear the field. Working sample code below:
TextFormField(
controller: _firstNameController,
textAlign: TextAlign.left,
cursorColor: Colors.white,
onChanged: (value) {
},
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'First Name',
suffix: GestureDetector(
onTap: () {
_firstNameController.clear();
},
child: Icon(Icons.clear)
)
),
),
Hope this helps.

Flutter - Hide hint text when Text Field have focus

I need to know how to hide the hint text when I focus on the text field. This is my code:
class _ContactoState extends State<Contacto> {
FocusNode focusMsj;
#override
void initState() {
super.initState();
focusMsj = FocusNode();
focusMsj.addListener(() {
if (!focusMsj.hasFocus) {
FocusScope.of(context).requestFocus(focusMsj);
}
});
}
TextField(
focusNode: focusMsj,
hintText: focusMsj.hasFocus ? ' ' : 'Hint Text',)
return WillPopScope(
child: Listener(
onPointerUp: (e) {
focusMsj.hasFocus ? FocusScope.of(context).requestFocus(FocusNode()): '';
},
Thank you
For doing that matter you need to make something like that
class Play extends StatefulWidget {
#override
_PlayState createState() => _PlayState();
}
class _PlayState extends State<Play> {
FocusNode focusNode = FocusNode();
String hintText = 'Hello , iam Hint';
#override
void initState() {
// TODO: implement initState
super.initState();
focusNode.addListener(() {
if (focusNode.hasFocus) {
hintText = '';
} else {
hintText = 'Hello , iam Hint';
}
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () {
print(focusNode.hasFocus);
}),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
focusNode: focusNode,
decoration: InputDecoration(
hintText: hintText,
),
),
TextField(
decoration: InputDecoration(
hintText: '!!',
),
),
],
),
),
);
}
}
Shortly i listened to TextField by its focusNode property . When TextField has focus i make hintText property equal empty String value
There is a property for that:
TextField(decoration: InputDecoration(hasFloatingPlaceholder: false));
Edit: The version above is deprecated, the new version is:
TextField(decoration: InputDecoration(floatingLabelBehavior: FloatingLabelBehavior.never,),),
One simple solution you can try is define labelText with FloatingBehavior.never
TextField(
decoration: InputDecoration(
labelText: "Search",
floatingLabelBehavior: FloatingLabelBehavior.never,
)
)
HintText will be shown when it is not focussed. On focus, hint text will disappear.
Simply, don't add the hintText in the InputDecoration and mention only the labelText: 'Label' alongside labelStyle if you want to change the style of the label.
TextField(
decoration: InputDecoration(
labelText: "Label",
labelStyle: TextStyle(
color: Colors.blueGrey,
),
floatingLabelBehavior: FloatingLabelBehavior.never,
)
)
My understanding is there is no way to implement it without custom code. Hiding hintText when focused with "border: InputBorder.none," gives perfect login widget example as FloatingLabelBehavior and having animated labelText just won't do. floatingLabelBehavior: FloatingLabelBehavior.never - helps in some situtations but not the exact thing we wanted. If you have labelText and hintText FloatingLabelBehavior.never is helpful to control hiding and showing hintText and animating labelText above the field. WIth custom code we have
String emailHintText = "E-mail";
on the top of state class. Then:
Container(
decoration: BoxDecoration(
border: Border.all(color: white),
borderRadius: BorderRadius.circular(5)),
child: Padding(
padding: EdgeInsets.all(10),
child:
Focus(
onFocusChange: (hasFocus) {
if (hasFocus) {
setState(() {});
emailHintText = "";
}
else {
setState(() {});
emailHintText = "E-mail";
}
},
child: TextFormField(
decoration: InputDecoration(
hintText: emailHintText,
border: InputBorder.none))));
Now, you should know that using setState is a bit costly operation and may not be the best option if not used for very important functionalities.
This works perfectly for me. Just add on InputDecoration ( floatingLabelBehavior: FloatingLabelBehavior.never) of TextField or TextFormField.
TextFormField( controller:_controller, decoration : InputDecoration( label: Text('Entrer your code here '), floatingLabelBehavior: FloatingLabelBehavior.never, ), );

Flutter TextField, how to use different style for label inside vs above the text field

I have the following TextField:
TextField(
decoration: InputDecoration(
labelStyle: TextStyle(
color: I_WANT_TO_CHANGE_THIS,
),
labelText: widget.label,
),
);
How do I change the color so that when it's inside the text field (a hint), it's GRAY, and when it's floating above the text field (being focused), it's BLACK.
Try using a FocusNode:
class _MyHomePageState extends State<MyHomePage> {
FocusNode _focusNode = FocusNode();
Color color;
#override
Widget build(BuildContext context) {
_focusNode.addListener(() {
setState(() {
color = _focusNode.hasFocus ? Colors.blue : Colors.red;
});
});
return Scaffold(
body: Center(
child: TextField(
focusNode: _focusNode,
decoration: InputDecoration(
labelText: 'Label',
labelStyle: TextStyle(
color: _focusNode.hasFocus ? Colors.blue : Colors.red,
)
),
autofocus: false,
),
)
);
}
}
Notice that in this particular example the textfield will always be in focus once selected, since there's only one textfield.