Reputation: 970
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?
Upvotes: 1
Views: 1635
Reputation: 439
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;
},
);
});
Upvotes: 2