Flutter-更改setState内部或外部的变量? [英] Flutter - change variables inside or outside setState?

查看:358
本文介绍了Flutter-更改setState内部或外部的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flutter Widget中更改状态时,这样做之间有什么区别

When changing the state in a Flutter Widget, are there any differences between doing this

_variable1 = true;
variable2 = 'abc';
setState(() => {});

或这个

setState(() => {
    _variable1 = true;
    variable2 = 'abc';
});

文档中几乎所有示例都使用最后一个,但我没有发现任何实际差异.在这两种情况下都设置了变量并更新了状态,但是我想知道是否存在一种情况,如果使用一种或另一种方法,则无法按预期工作.

Almost all the examples in the docs use the last one, but I didn't notice any pratical differences. The variables are set and the state is updated in both cases, but I am wondering if there is a scenario that something doesn't work as expected if use one or another.

推荐答案

根据扑朔迷离

According to the flutter docs, it is stated that:

通常建议仅将setState方法用于 包装实际的状态更改,而不是可能的任何计算 与更改相关联.

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的主体放入新构建的小部件中,而不将其与您的计算作为问题中的第一种方法进行混合会.

Mainly I think that it is for readability purposes, i.e, you need to put in the body of setState what is changing in the new build of the widget, without mixing that with your computations as the first method in your question does.

这篇关于Flutter-更改setState内部或外部的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆