Reputation: 124
Well it's probably a very simple question but I'm starting and I'm not able to find too much documentation about flutter...
import 'package:flutter/material.dart';
class AutoChangeField extends StatefulWidget {
@override
_AutoChangeFieldState createState() => _AutoChangeFieldState();
}
class _AutoChangeFieldState extends State<AutoChangeField> {
Color _color = Colors.black;
String _newValue = 'write something';
@override
Widget build(BuildContext context) {
return TextFormField(
initialValue: _newValue,
cursorColor: _color,
onChanged: (val){
setState(() {
_newValue = "It changed!";
_color = Colors.red;
});
},
);
}
}
Just the cursorColor swaps to red properly when you write something at the TextFormField, but the value of it does not. Value keeps being "write something + (what u writed)" instead of "It changed!". :(
Thanks you so much.
Upvotes: 0
Views: 1052
Reputation: 12713
You should use a TextEditingController
and set the initialValue of the TextEditingController
to "Write something"
Like this
class AutoChangeField extends StatefulWidget {
@override
_AutoChangeFieldState createState() => _AutoChangeFieldState();
}
class _AutoChangeFieldState extends State<AutoChangeField> {
Color _color = Colors.black;
TextEditingController controller = TextEditingController(text: "Write something");
@override
Widget build(BuildContext context) {
return TextFormField(
controller: controller,
cursorColor: _color,
onChanged: (val){
print(val);
controller.text = "It changed!";
setState(() {
_color = Colors.red;
});
},
);
}
}
NOTE: You cannot use the controller and initialValue at the same time.
Upvotes: 2
Reputation: 14205
You need to use 'controller' proeprty.
Define a controller like below :
TextEditingController myController = new TextEditingController();
Assign it to the TextFormField as :
TextFormField(
controller: myController,
Now, assign a new value as :
myController.text = "its changed";
Upvotes: 2