我做了一个提供程序来获取食物类的多个示例的求和值,并在按钮上显示求和值,但由于某种原因,除非我离开并返回页面或热加载,否则它不会显示。
我有一个列表userOrders,其中包含添加到购物车的所有项目,fold函数应该总结价格和数量的乘积,并在按钮上显示它。
- 食物**
class Food {
String imgUrl;
String desc;
String name;
String waitTime;
num score;
int price;
int pq;
int quantity;
bool favourited;
List<Map<String, String>> ingredients;
String about;
bool highlight;
Food(this.imgUrl, this.desc, this.name, this.pq, this.waitTime, this.score,
this.price, this.quantity, this.ingredients, this.about, this.favourited,
{this.highlight = false});
int pqProduct(Food food) {
pq = food.quantity * food.price;
return pq;
}
- 供应商**
class FavFood with ChangeNotifier {
int peeQee() {
int pqe =
userOrders.fold(0, (a, element) => a + element.pqProduct(element));
return pqe;
}
void update() {
notifyListeners();
}
}
- 按钮**
class NextButton extends StatefulWidget {
@override
State<NextButton> createState() => _NextButtonState();
}
class _NextButtonState extends State<NextButton> {
@override
Widget build(BuildContext context) {
return userOrders.isNotEmpty
? Container(
color: Colors.transparent,
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 5.0, 5.0),
height: 60,
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: const BorderSide(color: Colors.transparent),
),
),
),
child: Text(
'${context.read<FavFood>().peeQee}',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
onPressed: () {},
),
)
: const Text('');
}
}
该按钮应该更新价格时,一个项目被添加,但它没有,直到我重新加载Food
的示例
Food(
'assets/images/sha-modified.png',
'Most Recommended',
'Shawarma',
0,
'15 min',
4.5,
1500,
0,
[
{
'Flatbread': 'assets/images/flatbread-modified.png',
},
{'Cabbage': 'assets/images/cabbb-modified.png'},
{'Chicken': 'assets/images/chicken-modified.png'},
{'Sauce': 'assets/images/sauce-modified.png'},
],
'A sandwich of sliced lamb or chicken, vegetables, and often tahini wrapped in pita bread',
highlight: true,
false,
),
1条答案
按热度按时间7cjasjjr1#
您需要在构建方法中放置一个
context.watch<FavFood>()
,以便实际侦听notifyListeners()
所做的更改。另外,您的
onPressed
回调实际上是空的,您需要调用您的update()
方法来触发构建。