flutter自定义控件 - StatefulWidget获取当前State
  xx2YH4ad7R0N 2023年11月02日 77 0


问题描述

StatefulWidget作为一种状态可变的控件,其状态的改变通常是由State.setState进行的,但当我们需要在StatefulWidget之外改变它的状态时,因Widget的重新构造并不一定使得State重新构造,所以我们难以直接获取当前Widget所绑定的State,从而改变StatefulWidget的状态。

解决方案

常规方案

我们可以为StatefulWidget设置一个GlobalKey(),通过GlobalKey.currentState来获取当前绑定的State实例。示例如下:
 

class _Widget extends StatefulWidget {
final GlobalKey _key;
final double width;
final double height;

const _Widget(this.width, this.height, this._key) : super(key: _key);

@override
State<StatefulWidget> createState() => _State();

void setSize(double width, double height) {
var state = _key.currentState;
if (state is _State) {
state.setSize(width, height);
}
}
}

class _State extends State<_Widget> {
...
void setSize(double width, double height) {
setState(() {
_width = width;
_height = height;
});
}
...
}

此时就可以通过​​_Widget.setSize​​来改变该StatefulWidget的状态。

与此类似的方案可以参考:​​flutter通过GlobalKey在自定义Widget外部获取其state刷新页面_一叶飘舟的博客​

 另辟蹊径

只适用于使用StatefulWidget的一个实例。

对于一个StatefulWidget,其Widget实例可以有多个,但其State实例只有一个。因此当只使用该StatefulWidget的一个实例时(即页面上只有一个该自定义的StatefulWidget控件),可以通过静态字段来引用State实例。示例如下:
 

class _Widget extends StatefulWidget {
final double width;
final double height;

const _Widget(this.width, this.height, {Key? key}) : super(key: key);

@override
State<StatefulWidget> createState() {
return _State();
}

void setSize(double width, double height) {
_State.state?.setSize(width, height);
}
}

class _State extends State<_Widget> {
static _State? state;

_State() {
state = this;
}

void setSize(double width, double height) {
setState(() {
_width = width;
_height = height;
});
}

@override
void dispose() {
super.dispose();
state = null;
}

...
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  iD7FikcuyaVi   2023年11月30日   23   0   0 MacWindowsandroid
  b1UHV4WKBb2S   2023年11月13日   33   0   0 裁剪ideflutter
  b1UHV4WKBb2S   2023年11月13日   26   0   0 flutterDart
  zSWNgACtCQuP   2023年11月13日   29   0   0 ide
xx2YH4ad7R0N