假设我有两个用Flutter呈现的文本字段:"net price“和"gross price”。我想同步它们,这样当用户更新净价时,毛价就会自动计算和更新。当用户更改毛价时,应更新净价字段。如何在Flutter中实现这样的行为?
发布于 2021-01-23 06:46:23
我建议使用provider package来解决这个问题。
基本上,您创建了一个扩展ChangeNotifier并保存两个TextFields的值的类,然后为这两个文本小部件提供它,在一个公共的父小部件中使用:
ChangeNotifierProvider(
create: (context) => MyClass(),
child: MyApp(),
),现在,每当您更改其中一个TextFields时,只需调用MyClass中的一个函数,该函数将计算另一个TextField的新值。例如:
void calculate() {
// Some calculation and updating the values of the TextFields
notifyListeners();
}请注意notifyListeners()调用,它告诉侦听此模型的小部件进行重新构建。
要了解此模型,请将文本小部件包装在消费者中,如下所示:
return Consumer<MyClass>(
builder: (context, myClass, child) {
return Text("Total price: ${myClass.netPrice}");
});您可以从颤动状态管理tutorial中了解更多信息
https://stackoverflow.com/questions/65853533
复制相似问题