作为 flutter 的新手,使用时对我来说非常困惑setState
in Flutter
应用。在下面的代码中布尔值searching
和变量resBody
里面用的setState
。我的问题是为什么只searching
and resBody
在 setState 里面?为什么其他变量不可以呢?
var resBody;
bool searching = false,api_no_limit = false;
String user = null;
Future _getUser(String text) async{
setState(() {
searching = true;
});
user = text;
_textController.clear();
String url = "https://api.github.com/users/"+text;
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept":
"application/json"});
setState(() {
resBody = json.decode(res.body);
});
}
根据docs https://docs.flutter.io/flutter/widgets/State/setState.html:
调用 setState 会通知框架此对象的内部状态已更改,可能会影响此子树中的用户界面,这会导致框架安排此 State 对象的构建。
因此,如果小部件的状态发生变化you have打电话setState
触发视图的重建并立即查看新状态隐含的更改。
无论如何,下面的片段是等效的。
第一种情况(直接形成flutter create <myproject>
):
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
第二种情况:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
_counter++;
setState(() {});
}
我不知道第一种情况是否是常规使用方式的原因setState
,我想说是因为代码的可读性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)