Flutter:setState() 中的代码重要吗?
Flutter: Does it matter what code is in setState()?
当我们想要重建 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.
它没有明确说明调用是在函数内还是在函数外是不同的。但是建议放在里面。在我看来,如果将更改放在 setState
函数
的旁边,它也更具可读性和逻辑性
当我们想要重建 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.
它没有明确说明调用是在函数内还是在函数外是不同的。但是建议放在里面。在我看来,如果将更改放在 setState
函数