I am making a profile editing page in my program. I am using initialValue in TextFormField but it is not showing username from firebase. I'm creating a controller in initState, it still doesn't show. My codes are as follows. What should I do for this?
class _EditProfileState extends State<EditProfile> {
var userData = {};
TextEditingController _usernameController = TextEditingController();
TextEditingController t3 = TextEditingController();
TextEditingController _bioController = TextEditingController();
@override
void initState() {
super.initState();
_usernameController = new TextEditingController(text: userData['username']);
getData();
}
TextFormField
TextFormField(
keyboardType: TextInputType.name,
controller: _usernameController,
autofocus: false,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.supervised_user_circle_rounded),
hintText: userData['username'],
labelText: userData['username'],
contentPadding:
const EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0)),
)),
CodePudding user response:
Use TextEditingController.fromValue()
like this
late final TextEditingController _usernameController;
@override
void initState() {
super.initState();
_usernameController = TextEditingController.fromValue(
TextEditingValue(text: userData['username']??''));
}
And make sure you are getting data on userData
.
CodePudding user response:
I can see opportunity to solve this problem, but i'm not sure since idk how your getData() function work, if you can translate this logic with your code i think you can solve it.
for now you try to write userData['username'] at _usernameController in initState while userData still "Empty", and then you call getData()
which i assume you're trying to get user's data and fill userData on it... after getData got called, for sure your _usernameController stays empty because there is no further action to update your _usernameController...
Here is my simple solution
lets say your getData() function will be look like this, and make sure getData() only called on initState()
to prevent _usernameController got updated accidentally
void getData() async {
... Do some stuff to load data ...
setState((){
userData = data;
///Do your things here instead...
_usernameController.text = userData['username'] ?? "";
});
}