How to use setState method for only one widget in flutter?

Viewed 7352

On clicking on any point in the below graph, I want to show some information related to that point. But when I use setState method to update the below information on click event, the graph is getting rebuilt. I want to zoom in at a certain time in this time-series graph, but the rebuilding graph is a problem and not able to see labels on graph. How to use the setState method to update the below information without redrawing the graph?

In the below image Angle value should be 15.0 whereas it's not updating without setState

enter image description here

5 Answers

You could wrap your widget with StatefulBuilder:

A platonic widget that both has state and calls a closure to obtain its child widget.

The StateSetter function passed to the builder is used to invoke a rebuild instead of a typical State's State.setState.

Here is an example from the docs:

await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

What I do to stop rebuilding some widgets is I move that widget into its own stateful widget. So it will not rebuild when it's parent rebuild. And to communicate between them I use callback functions or bloc pattern. So what you can do is you can move the graph to a seperate stateful widget and on cilck event you can pass the data through a fucntion callback to its parent.

You could use the Provider widget with its Consumer pattern to reduce which parts of the tree are rebuilt on changes.

Your question is based on a misconception.

What you asked is "don't call build again on XX widget".

But you're looking for is for two methods to not be called:

  • RenderObject.layout
  • RenderObject.paint

setState has no influence on that.

Calling setState won't necessarily repaint the associated widget tree. And the opposite is true too, there's no need for a setState for the widget tree to be repainted.

What you're looking for is for things like RepaintBoundary, which allows part of the tree to not repaint if not needed.

Related