Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 242
Harsha Vardhan Avatar asked Oct 16 '19 10:10

Harsha Vardhan


2 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);
                },
              );
            }),
          );
        },
      ),
    );
  },
);
like image 199
Pablo Barrera Avatar answered Sep 21 '22 21:09

Pablo Barrera


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.

like image 40
Praneeth Dhanushka Fernando Avatar answered Sep 21 '22 21:09

Praneeth Dhanushka Fernando