[英]Flutter setState() method calling
As I am a new dev in Flutter it's very confusing me to when should I call setState() ?, If I call this entire application is reloading (redrawing view) in build(). 由于我是Flutter的新开发人员,这让我很困惑何时应调用setState()?,如果我调用此方法,则整个应用程序都将在build()中重新加载(重绘视图)。 I want to update one TextView widget value in tree widgets structure 我想在树小部件结构中更新一个TextView小部件值
Here is example. 这是例子。 On click on fab you recreate only _MyTextWidget
在fab上单击时,您仅重新创建_MyTextWidget
StreamController<int> _controller = StreamController<int>.broadcast();
int _seconds = 1;
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.cyan.withOpacity(0.3),
width: 300.0,
height: 200.0,
child: _MyTextWidget(_controller.stream)),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.add(_seconds++);
},
child: Icon(Icons.add),
),
);
}
...
class _MyTextWidget extends StatefulWidget {
_MyTextWidget(this.stream);
final Stream<int> stream;
@override
State<StatefulWidget> createState() => _MyTextWidgetState();
}
class _MyTextWidgetState extends State<_MyTextWidget> {
int secondsToDisplay = 0;
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: widget.stream,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
return snapshot.hasData ? Text(snapshot.data.toString()) : Text('nodata');
});
}
}
To make it simple, SetState() {}
invalidates the widget in which it is called and forces the widget to rebuild itself by calling build()
. 为简单SetState() {}
, SetState() {}
使在其中被调用的窗口小部件无效,并通过调用build()
强制窗口小部件重建自身。 That means that every child widgets are being rebuilt. 这意味着每个子小部件都将被重建。
There are other methods you can use to pass data to a widget down a tree and make it rebuilt itself (and all its chidlren) than using SetState () {}
. 与使用SetState () {}
相比,还有其他方法可用于将数据传递到树上的小部件并使其自身(及其所有子类)重建。 Those are really helpfull, especially if the widget you want to rebuilt is far away from yours in the widget tree. 这些确实有用,特别是如果要重建的小部件与小部件树中的部件相距甚远。
One of them is the example provided by @andrey-turkovsky that uses a combination of StreamBuilder
and a Stream
. 其中之一是@ andrey-turkovsky提供的示例,该示例结合使用StreamBuilder
和Stream
。 The StreamBuidler
is a widget that rebuilt itself when there is an interaction in a Stream
. StreamBuidler
是一个小部件,当Stream
存在交互时,它会自行重建。 Based on that, the idea is to wrap your TextView
in a StreamBuilder
, and use the stream to sent the data you want your TextView
to display. 基于此,我们的想法是将TextView
包装在StreamBuilder
,并使用流发送您希望TextView
显示的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.