gpt4 book ai didi

dart - Flutter:setState() 中的代码是否重要?

转载 作者:IT老高 更新时间:2023-10-28 12:33:11 24 4
gpt4 key购买 nike

当我们想要重建 StatefulWidget 时,我们调用 setState(),但我们输入的代码是在该函数内部还是外部,这真的很重要吗?

这是:

class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
setState(() {
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
}
}

和这个一样:

class _ShoppingListState extends State<ShoppingList> {
Set<Product> _shoppingCart = new Set<Product>();
void _handleCartChanged(Product product, bool inCart) {
if (inCart)
_shoppingCart.add(product);
else
_shoppingCart.remove(product);
});
setState((){});
}
}

最佳答案

根据docs :

@protected

void setState (
VoidCallback fn
)

Notify the framework that the internal state of this object has changed.

Whenever you change the internal state of a State object, make the change in a function that you pass to setState:

setState(() { _myState = newValue });

The provided callback is immediately called synchronously. It must not return a future (the callback cannot be async), since then it would be unclear when the state was actually being set.

还有

Generally it is recommended that the setState method only be used to wrap the actual changes to the state, not any computation that might be associated with the change.

它没有明确说明在函数内部或外部调用 is 是否不同。但它确实建议把它放在里面。而且在我看来,如果您将更改放在 setState 函数

中,它也更具可读性和逻辑性

关于dart - Flutter:setState() 中的代码是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com