如何解决更新 Provider 子类的属性
这里有几个类。
abstract class Vehicle {
Vehicle(this.owner);
String owner;
}
class Car extends Vehicle {
Car(String owner) : super(owner);
int fule = 0;
void fillFule(int fule) {
this.fule += fule;
}
}
class Cycle extends Vehicle {
Cycle(String owner) : super(owner);
int chainDurability = 50;
void changeChain() {
this.chainDurability = 50;
}
}
还有一个提供者。
class VehicleProvider extends ChangeNotifier {
List<Vehicle> vehicles = [];
}
更新Vehicle
的属性很容易
class VehicleProvider extends ChangeNotifier {
List<Vehicle> vehicles = [];
/// I usually do that
void changeOwner(int index,String newOwner) {
vehicles[index].owner = newOwner;
notifyListeners();
}
}
但是如何更新 Car
或 Cycle
的属性?
我无法通过 Car
公开 Cycle
和 VehicleProvider
的控制器。因为会有很多 Vehicle
的子类。
所以我想手动调用 notifyListeners()
,就像 setState()
一样。它有效,但似乎是反模式。
class VehicleProvider extends ChangeNotifier {
...
/// I added empty notifyListeners.
void doNotifyListeners() {
notifyListeners();
}
}
class CarCtrlPanel extends StatelessWidget {
CarCtrlPanel(this.car);
final Car car;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text('${car.owner}s car'),Row(
children: [
Text('fule: ${car.fule}'),FlatButton(
onpressed: () {
car.fillFule(10);
/// And call it manually
Provider.of<VehicleProvider>(context,listen: false)
.doNotifyListeners();
},child: Text('fill fule'),),],);
}
}
class CycleCtrlPanel extends StatelessWidget {
CycleCtrlPanel(this.cycle);
final Cycle cycle;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Text('${cycle.owner}s cycle'),Row(
children: [
Text('chainDurability: ${cycle.chainDurability}'),FlatButton(
onpressed: () {
cycle.changeChain();
/// Same as above
Provider.of<VehicleProvider>(context,);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。