I have the following code, shown below where every time I make changes to a text field, a function gets called, in my case doSomething(). However, I assumed that since I bound the value of the text to a variable, if that variable were to get updated, the textfield text would also update. This is not happening, and my question is, what would be the simplest way to make the textfield update its text every time the corresponding variable changes.
Edit: Just to clarify, I have no problem getting the doSomething() function to update other parts of the code, I am looking for the inverse where an external variable changes the text of the textfield
import 'package:flutter/material.dart';
class DynamicTextField extends StatefulWidget {
const DynamicTextField(
{
required this.value,
Key? key})
: super(key: key);
final double value;
@override
State<DynamicTextField> createState() =>
_DynamicTextFieldState(value);
}
class _DynamicTextFieldState extends State<DynamicTextField> {
_DynamicTextFieldState(this.value);
final double value;
late TextEditingController textChanged;
@override
void initState() {
textChanged = TextEditingController(text: value.toString());
super.initState();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: textChanged,
onChanged: (text) {
doSomething();
},
);
}
}
CodePudding user response:
you can change the TextField
value with the textChanged
controller you set to that widget.
String stringVariable = "some value";
textChanged.text = stringVariable;
you can then update the state with a normal SetState(() {})
, and it should update the value in TextField
CodePudding user response:
Your value is declared as final. Meaning it can only be set once. Try removing the final declaration.
I also see you’re also declaring the value variable twice, instead of referencing the original value variable.
The second declaration should be in the widgets build method & should = widget.value.