This link here describes how to set an initial value to a TextField widget. I need to be able to set a value (possibly overriding any existing value) if a CheckboxListTile is checked, and clear the value if unchecked. How can I achieve this?
What I’ve tried: (Seems the question is pretty much solved with this update. Now, I want to know if assigning controller = TextEditingController();
and again in initState and later again in setState as controller = TextEditingController(text: "Default Value 01");
and controller = TextEditingController(text: "");
a good practice?)
class _MyHomePageState extends State<MyHomePage> {
late TextEditingController controller;
String text = "";
@override
void initState() {
super.initState();
controller = TextEditingController();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
bool? _isChecked = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
onSubmitted: (String value) {
setState(() {
text = controller.text;
});
},
),
CheckboxListTile(
value: _isChecked,
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool? newValue) {
setState(() {
_isChecked = newValue;
if (_isChecked == true) {
//text = "Default Value 01";
controller =
TextEditingController(text: "Default Value 01");
}
if (_isChecked == false) {
//text = "";
controller = TextEditingController(text: "");
}
});
},
title: Text("Checkbox"),
),
const SizedBox(
height: 20,
),
Text(text),
],
),
),
));
}
}
2
Answers
To set a text to
TextField
use_controller.text = "<Your-Text>"
Example
You are initializing the controller again which is not recommended instead just change the value to text property of controller like this: