本文介绍了在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 veriable?

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来触发视图重建,并立即查看新状态所隐含的更改.

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时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 18:50