How to change TextFormField initialValue dynamically?
668
You can use TextEditingController in this case.
TextEditingController _controller = TextEditingController();
Consumer<ButtonMode>(builder: (context, buttonMode, child) {
if(buttonMode.weight != null && _controller.text != buttonMode.weight){ // or check for the null value of button mode.weight alone
_controller.text = buttonMode.weight ?? '' ;
}
return TextFormField(
controller : _controller,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter weight';
}
return null;
},
);
});
Author by
João Pedro
Updated on December 31, 2022Comments
-
João Pedro over 1 year
I'm trying to use a value from a provider model to update the initialValue of a TextFormField, but the initialValue doesn't change.
import 'package:flutter/material.dart'; import 'package:new_app/models/button_mode.dart'; import 'package:provider/provider.dart'; class EditWeightTextField extends StatelessWidget { const EditWeightTextField( {Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<ButtonMode>(builder: (context, buttonMode, child) { return TextFormField( initialValue: buttonMode.weight.toString(), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter weight'; } return null; }, ); }); } }
if instead of a TextFormField I use a
Text(${buttonMode.weight}')
then the text is updated properly. What can I do to make it work with the TextFormField?-
HaSnen Tai over 2 yearsI would recommend you to use
TextEditingController(text: 'Initial value');
, Let me know if you need a complete solution -
João Pedro over 2 yearsI would appreciate a complete solution
-