Stopping a function in flutter


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)));

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


The first button:

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

The second button:

 onPressed: () {

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

Thanks in advance!


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


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);

And when you want to stop adding graphs Do.

onPressed: () { 
if(_timer !=null) {

Answered By – hrushikesh kuklare

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *