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

问题描述

作为 flutter 的新手,在 Flutter 应用程序中使用 setState 时,我很困惑.在下面的代码中,setState 中使用了 boolean searching 和 var resBody.我的问题是为什么在 setState 中只有 searchingresBody ?为什么其他变量不可变?

var resBody;bool 搜索 = false,api_no_limit = false;字符串用户 = 空;未来 _getUser(字符串文本)异步{设置状态((){搜索 = 真;});用户 = 文字;_textController.clear();字符串 url = "https://api.github.com/users/"+text;var res = 等待 http.get(Uri.encodeFull(url), headers: {Accept":应用程序/json"});设置状态((){resBody = json.decode(res.body);});}
解决方案

根据 文档:

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

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

无论如何,以下代码段是等效的.

第一种情况(直接形成flutter create ):

class _MyHomePageState 扩展 State{int_counter = 0;void _incrementCounter() {设置状态((){//这个对 setState 的调用告诉 Flutter 框架某些东西已经//在此状态下发生更改,导致它重新运行下面的构建方法//以便显示可以反映更新的值.如果我们改变//_counter 不调用setState(),那么build方法就不会//再次调用,所以似乎什么都没有发生._计数器++;});}

第二种情况:

class _MyHomePageState 扩展 State{int_counter = 0;void _incrementCounter() {_计数器++;setState(() {});}

我不知道是为什么,如果第一种情况是使用 setState 的常规方式,我会说是因为代码的可读性.

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);
  });
}
解决方案

According to the docs:

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.

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++;
    });
  }

second case:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    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-11 01:39