Problem
I'm doing a chat. I want the program to try to get messages again every 5 seconds if there are no messages.
My solution
I'have created a Timer in my stateful widget.
Timer timer;
When I build a widget, I check for messages. If there are none, I start the timer. I want the timer to stop at the next check, in case of existing messages
void onBuild() {
if (state.messages.isEmpty) {
_checkEmptyMessages();
timer = Timer.periodic(
Duration(seconds: 5), (Timer t) => _checkEmptyMessages());
}
}
void _checkEmptyMessages() {
print('MES789 ${state.messages.isEmpty}');
if (state.messages.isEmpty) {
add(ChatEventLoadFirstPage()); // This adds an event to the BLoC
} else {
if (timer != null) timer.cancel();
timer = null;
}
}
Also I've tried
I've tried to remove timer = null;
and await for timer.cancel();
, but it didn't help.
Actual output
So in the Debug Console I get this every 5 seconds:
I/flutter (13387): MES789 false
I/flutter (13387): MES789 false
I/flutter (13387): MES789 false
I/flutter (13387): MES789 false
Question
How can I stop the Timer?
CodePudding user response:
this code is dead code, it will never work because you have if (state.messages.isEmpty)
before _checkEmptyMessages()
and if (state.messages.isEmpty)
again, try to remove first if (state.messages.isEmpty)
CodePudding user response:
Because 'Timer.periodic' is called, new Timer instance is created and stored same timer variable.
It means that not canceled timer's instance will be lost when 'Timer.periodic' is called.
So you need to check whether Timer instance is exist.
void onBuild() {
if (state.messages.isEmpty) {
if (timer == null) {
timer = Timer.periodic(
Duration(seconds: 5), (Timer t) => add(ChatEventLoadFirstPage()));
}
} else {
if (timer != null) timer.cancel();
timer = null;
}
}