Stopping a function in flutter

Issue

I am new to flutter and I have a problem with a flutter function. It adds data to graph and I programmed a button to start updating the graph. How do I stop it? I created another button and I want to program it to stop the function that adds the graph.

The function:

void updateDataSource(Timer timer) {


chartData.add(LiveData(time++, (y)));
chartData.removeAt(0);

_chartSeriesController.updateDataSource(
    addedDataIndex: chartData.length - 1, removedDataIndex: 0);

}

The first button:

onPressed: () {
                     Timer.periodic(const Duration(seconds: 1), updateDataSource);
                  },

The second button:

 onPressed: () {
                    
                    chartData.clear();
                    
                    
                  },

I put chartData.clear() but that clears everything and I am unable to call back the function again.

Thanks in advance!

Solution

This is due to your Timer.periodic function which is running every second

Solution:

Create a state timer variable

Timer? _timer;

Assign a value to the timer when you first onPressed

onPressed: (){
_timer =  Timer.periodic(const Duration(seconds: 1), updateDataSource);
setState((){});
},

And when you want to stop adding graphs Do.

onPressed: () { 
if(_timer !=null) {
_timer.cancel();
}
},

Answered By – hrushikesh kuklare

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.