简体   繁体   中英

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(). I want to update one TextView widget value in tree widgets structure

Here is example. On click on fab you recreate only _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() . 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 () {} . 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 . The StreamBuidler is a widget that rebuilt itself when there is an interaction in a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM