How to deal with unwanted widget build?

前端 未结 3 1961
长发绾君心
长发绾君心 2020-11-21 11:28

For various reasons, sometimes the build method of my widgets is called again.

I know that it happens because a parent updated. But this causes undesired

3条回答
  •  佛祖请我去吃肉
    2020-11-21 12:04

    Flutter also has ValueListenableBuilder class . It allows you to rebuild only some of the widgets necessary for your purpose and skip the expensive widgets.

    you can see the documents here ValueListenableBuilder flutter docs
    or just the sample code below:

      return Scaffold(
      appBar: AppBar(
        title: Text(widget.title)
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You have pushed the button this many times:'),
            ValueListenableBuilder(
              builder: (BuildContext context, int value, Widget child) {
                // This builder will only get called when the _counter
                // is updated.
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text('$value'),
                    child,
                  ],
                );
              },
              valueListenable: _counter,
              // The child parameter is most helpful if the child is
              // expensive to build and does not depend on the value from
              // the notifier.
              child: goodJob,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.plus_one),
        onPressed: () => _counter.value += 1,
      ),
    );
    

提交回复
热议问题