问题描述
我有一个 ProperyListPage,在点击的每个列表项上,这是它执行的操作。
Navigator.push(
context,MaterialPageRoute(
builder: (context) => ChangeNotifierProvider.value(
value: property,child: PropertyPage(),),);
}
在PropertyPage里面我有BottomNavigationBar,当你点击EditBottomNavigationBarItem时,它会像这样进入PropertyEditTab
PropertyEditTab(),
在 PropertyEditTab 里面我有一个像这样的表单小部件
child: Form(
key: _formKey,child: Column(
children: [
PropertyForm(
callback: saveProperty,...
)...
我的 saveProperty 回调看起来像这样
void saveProperty(BuildContext context) async {
if (_formKey.currentState.validate()) {
Propertyviewmodel _propertyVM = Provider.of<Propertyviewmodel>(context,listen: false);
savingproperty();
final isSaved = await _propertyVM.updateproperty();
if (isSaved) {
propertySaved();
} else {}
}
}
updateProperty 方法像这样更新 Firestore
class Propertyviewmodel extends ChangeNotifier {
...
Future<bool> updateproperty() async {
bool isSaved = false;
User user = _firebaseAuth.currentUser;
print(uid);
final property = Property(
user.email,...
);
try {
await _firestore
.collection(Constants.propertyCollection)
.doc(property.uid)
.update(property.toMap());
isSaved = true;
} on Exception catch (e) {
print(e);
message = 'Property not saved.';
} catch (e) {
print(e);
message = 'Error occurred';
}
notifyListeners();
return isSaved;
}
...
}
那么我的每一个表单域都是这样的
FormTextField(
name: 'address_line_1',hintText: 'Address Line 1',initialValue: propertyVM.addressLine1 ?? '',onChanged: (value) {
propertyVM.addressLine1 = value;
},
这是我的按钮保存属性
ThemeButton(
text: 'Save Property',buttonColor: Constants.kPrimaryColor,textColor: Colors.white,onPress: () => widget.callback(context),
问题在于,当调用 notifyProviders() 时,原始 Propertyviewmodel 属性 未更新,我无法弄清楚我做错了什么。
预先感谢您的帮助。
解决方法
我们在 slack 频道上写作。
我认为原因是因为在 FormTextField
小部件中将其更改为:
FormTextField(
name: 'address_line_1',hintText: 'Address Line 1',initialValue: propertyVM.addressLine1 ?? '',onChanged: (value) {
propertyVM.updateAdressLine(value);
},),
并在您的 PropertyViewModel
中创建一个函数
void updateAdressLine() {
adressLine1 = value;
notifyListeners();
}
这是因为从您的 FormTextField 中,您只是在更改值。您需要将更改打包到一个方法中,以便您可以一次更改值和 notifyListeners。