当我使用图标按钮调用 toggleFavorite 函数时,状态正在更改,但 ui 没有更新,但当我 热重载 时,它会更新。我在 stackoverflow 上检查了一些类似的问题,但我无法弄清楚。
class ProductsNotyfier extends StateNotifier<List<Product>> {
ProductsNotyfier()
: super([
Product(
id: 'p1',
title: 'Red Shirt',
description: 'A red shirt - it is pretty red!',
price: 29.99,
imageUrl:
'https://images.unsplash.com/photo-1602810320073-1230c46d89d4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80',
),
Product(
id: 'p2',
title: 'Trousers',
description: 'A nice pair of trousers.',
price: 59.99,
imageUrl:
'https://images.unsplash.com/photo-1603252110971-b8a57087be18?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80',
),
]);
List<Product> get items {
return [...state];
}
toggleFavorite(index) {
items[index].isFavotie = !items[index].isFavotie;
}
您需要更改
state
而不是 items
:
toggleFavorite(index) {
state[index].isFavotie = !state[index].isFavotie;
state = [...state];
}
热重载保留应用程序状态。它更快,因为它不会重新运行
main()
或````initState()```。如果要热重启应用程序状态,请在 VSCode 中调试模式下的终端中使用热重启“R”(大写 R)或(在 Android Studio 中为 ⇧⌘\,在 VSCode 中为 ⇧⌘F5)。请参阅文档此处。
状态应该是不可变的。使用
@immutable
或 lib @freezed
作为 Product
。请参阅此处。
toggleFavorite(index) {
state = [
for (final (i, product) in state.indexed)
if (i == index)
product.copyWith(isFavotie : !product.isFavotie )
else
product,
];
}