I have a simple widget, using Provider and trying to understand why it will not rebuild.
From my understanding (obviously wrong) because my widget is 'watching' postCode on the AddressViewModel, when changing the value as below, my widgets build method should be called and the widget rebuilt. What am I missing here? Why does context.watch not do as i expect and rebuild?
@override
Widget build(BuildContext context) {
var addressViewModel = Provider.of<AddressViewModel>(context);
return Container(
child: Column(
children: [
Text(context.watch<AddressViewModel>().postCode),
TextFormField(
onChanged: (value) {
//should this trigger rebuild? If not, why not as I am watching this above.
addressViewModel.postCode = "a new value";
//if I do setState(){} here, then it does rebuild, but should this rebuild without
//this as I am watching the postCode value above?
},
),
],
),
);
}
}
CodePudding user response:
You can modify the class with ChangeNotifier
class AddressViewModel with ChangeNotifier {
String address1 = "";
late String postCode = "my initial value";
void update({String? postCode, String? address1}) {
this.postCode = postCode ?? this.postCode;
this.address1 = address1 ?? this.address1;
notifyListeners();
}
}
And provider will be
providers: [
ChangeNotifierProvider(create: (_) => AddressViewModel()),
],
Now
TextFormField(
onChanged: (value) {
addressViewModel.update(postCode: value);
},
),
CodePudding user response:
in order to rebuild a widget, you should call the setState method.