空置状态有什么意义? [英] Empty set state what is the point?

查看:103
本文介绍了空置状态有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在不为变量设置新值的情况下调用setState的要点.

I want to know the point behind calling setState without setting a new value to the variables.

  readLocal() async {
    prefs = await SharedPreferences.getInstance();
    id = prefs.getString('id') ?? '';
    if (id.hashCode <= peerId.hashCode) {
      groupChatId = '$id-$peerId';
    } else {
      groupChatId = '$peerId-$id';
    }

    setState(() {});
  }

推荐答案

我会说这只是一个惯例.上面可以改写为

I would say it's just a convention. The above can be re-written as

readLocal() async {
  prefs = await SharedPreferences.getInstance();
  setState(() {
    id = prefs.getString('id') ?? '';
    if (id.hashCode <= peerId.hashCode) {
      groupChatId = '$id-$peerId';
    } else {
     groupChatId = '$peerId-$id';
   }
  });
}

两者都会做同样的事情.对state variable进行突变后再调用setState(() {})看起来很简洁而且很容易实现.

Both will do the same thing. Calling setState(() {}) after mutating the state variable looks neat and reabable.

根据setState实现部分,将按顺序排列下面的内容.

As per the implementation section of setState, it will below things in order.

  1. 断言.如果任何断言失败,则引发异常并在那里停止.
  2. 执行回调函数(final dynamic result = fn() as dynamic;)
  3. 要求框架重建(_element.markNeedsBuild();)
  1. Assertions. If any assert fails, throws exception and stops there.
  2. Execute the callback function (final dynamic result = fn() as dynamic;)
  3. Ask framework to rebuild(_element.markNeedsBuild();)

这篇关于空置状态有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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