Flutter:How to automatically clear my TextFields? - flutter

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.

Related

Why in Flutter, when I go to another page, the text in TextField disappears?

I enter text in TextField. When I click a button to go to another page and back, the text in the TextField disappears. Has anyone encountered this problem and can give me some advice?
My code:
Column(
children: [
ListTile(
onTap: () async {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => …)); // In fact, I used go_router, just replaced it with the Navigator that everyone should know
},
leading: const Icon(Icons.location_pin, color: Colors.black),
title: Text("Location"),
),
ListTile(
leading: const Icon(Icons.message, color: Colors.black),
title: TextFormField(
controller: messageController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Message",
),
),
),
],
),
Feel free to leave a comment if you need more information.
Why in Flutter, when I go to another page, the text in TextField disappears? I would appreciate any help. Thank you in advance!
This is because you create the TextEditingController when you navigate to this page so it will be created with empty text.
So you can make the controller global not inside StatefulWidget.
import 'package:flutter/material.dart';
class SearchScrean extends StatefulWidget {
const SearchScrean({super.key});
#override
State<SearchScrean> createState() => _SearchScreanState();
}
class _SearchScreanState extends State<SearchScrean> {
// you probably initialize the controller here or in initState.
TextEditingController messageController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
TextFormField(
controller: messageController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Message",
),
),
]),
);
}
}
See the comment.
You have to initialize it outside like this or use a state management package like bloc or provider :
import 'package:flutter/material.dart';
// initialize it here or in another global file
TextEditingController messageController = TextEditingController();
class SearchScrean extends StatefulWidget {
const SearchScrean({super.key});
#override
State<SearchScrean> createState() => _SearchScreanState();
}
class _SearchScreanState extends State<SearchScrean> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
TextFormField(
controller: messageController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Message",
),
),
]),
);
}
}
and when you don't want it anymore dispose it using messageController.dispose()

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.

How to disable mobile keyboard action key using Flutter?

I just need to disable the action button while the search query is empty. I'm not sure if this is possible with native Flutter.
Does this need to be done with each platform specifically? (iOS / Android)
You have a couple of options.
You can create a new focus:
FocusScope.of(context).requestFocus(new FocusNode())
Example:
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: ....,
)
)
)
}
The other option is to release the existing focus:
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
There is also a package: keyboard_dismisser
You just need to add a FocusNode to your TextFormField and request focus for it if the user presses the submit button on the keyboard when the field is empty. Here is a complete example:
class KeyboardKeeper60943209 extends StatefulWidget {
#override
_KeyboardKeeper60943209State createState() => _KeyboardKeeper60943209State();
}
class _KeyboardKeeper60943209State extends State<KeyboardKeeper60943209> {
List<String> items = List.generate(20, (index) => 'item $index');
TextEditingController _textEditingController = TextEditingController();
FocusNode _focusNode = FocusNode();
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: TextFormField(
focusNode: _focusNode,
controller: _textEditingController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search),
labelText: 'Search',
hasFloatingPlaceholder: false,
),
// This is the key part
onFieldSubmitted: (value) {
if(value == ''){
_focusNode.requestFocus();
}
},
),
),
FlatButton(onPressed: search, child: Text('Search'))
],
),
Expanded(
child: Container(
child: ListView.builder(
itemBuilder: (context, index){
return ListTile(
title: Text(items[index]),
subtitle: Text(items[index]),
);
}
),
),
),
],
);
}
void search(){
print('search');
}
}
TextFormField(
readOnly: true,
showCursor: false,
controller: consName,
decoration: InputDecoration(
hintText: 'Enter Name',
labelText: 'Username',
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.deepPurple,
width: 2,
),
),
),
),
Very Simple & Easy Use "readOnly: true" for disabling keyboard and if you don't want pointer or cursor then "showCursor: false". That's it, hope this'll work. Eat Sleep Workout Code Repeat. Happy Coding😊.
You can simply use textInputAction: TextInputAction.none on the TextField.

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, ), );

How do I create padding inside a list of text fields?

I am trying to create a registration widget. Most of the work I have done is finished and works.
I only have some issues with padding between my listed textfields.
How do I create a padding?
According to stack overflow this post is mostly code so here is some plain text because I really cannot say more about this, I have aksed my question and provided my code.
var entries = [];
class RegisPage extends StatefulWidget {
#override
_RegisPageState createState() => _RegisPageState();
}
class _RegisPageState extends State<RegisPage> {
#override
Widget build(BuildContext context) {
Map<String,TextEditingController> textEditingControllers = {};
var textFields = <TextFormField>[];
entries.forEach((str) {
var textEditingController = TextEditingController();
textEditingControllers.putIfAbsent(str, ()=>textEditingController);
return textFields.add(
TextFormField(
controller: textEditingController,
decoration:
InputDecoration(
labelText: str,
border:
OutlineInputBorder(
borderRadius:
BorderRadius.circular(25.0)
)
),
),
);
});
return Scaffold(
appBar: AppBar(
title: Text('Registration'),
),
body:Center(
child:
SingleChildScrollView(
child:
Column(
children:[
Column(children:textFields),
RaisedButton(
child: Text("Register"),
onPressed: (){
entries.forEach((str){
print(textEditingControllers[str].text);
});
}
)
]
)
)
)
);
}
}
If you want to add spacing you can just wrap the TextFormField with padding like this:
Padding(
padding: EdgeInsets.fromLTRB(left, top, right, bottom),
child: TextFormField(
controller: textEditingController,
decoration: InputDecoration(
labelText: str,
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(25.0)
)
),
),
),
Then instead of having a list of TextFormField you could do List<Widget>
Like this:
var textFields = <Widget>[];
Everything should still work the same, but now you can specify padding/spacing on all sides.
Hope this helps!