何时在Flutter中使用setState? [英] When do I use setState in Flutter?

查看:167
本文介绍了何时在Flutter中使用setState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为扑朔迷离的新手,在Flutter应用程序中使用setState时,对我来说很困惑.在下面的代码中,在setState内部使用的布尔searching和var resBody.我的问题是,为什么setState中只有searchingresBody?为什么其他人不可变?

As newbie in flutter it's very confusing for me when use setState in Flutter application. In below code boolean searching and var resBody used inside setState. My question is why only searching and resBody inside setState? Why not others variable?

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 :

调用setState会通知框架此对象的内部状态已更改,该方式可能会影响此子树中的用户界面,这会导致框架为该State对象安排构建.

Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

因此,如果窗口小部件的状态发生变化,您必须调用setState来触发视图重建,并立即查看新状态所隐含的更改.

So if the state of the widget changes you have to call setState to trigger a rebuild of the view and see immediatly the changes implied by the new state.

无论如何以下片段都是等效的.

Anyhow the below snippets are equivalent.

第一种情况(直接来自flutter create <myproject>):

first case (directly form 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的常规方式,我会说是因为代码的可读性.

What I don't know is the reason why and if the first case is the conventional way to use setState, I would say because of readability of code.

这篇关于何时在Flutter中使用setState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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