Flutter: Timer can not stop

980 Views Asked by At

My code is below. I try to close this timer. timer could not close. What can I do to close this timer? I need help immediatly.

Timer timerHttp;

@override
void initState() {
    timerHttp = Timer.periodic(new Duration(seconds: 10), (timerHttp) async {
      print("girdi yine asdadasd");
      final response = await http.get(
        "http://xxxxxxxxxxxxxxxxxxxxxxxxx",
      );
      if (response.statusCode == 200) {
        setState(() {
          var responseJson = json.decode(response.body);
          cm100Datas = responseJson;
          saat = [];
          l1voltState = [];
          l2voltState = [];
          l3voltState = [];
          l1akimState = [];
          l2akimState = [];
          l3akimState = [];
          for (var item in cm100Datas) {
            saat.add(saatFormat.parse(item["saat"]));

            l1voltState.add(double.parse(item["l1volt"]));
            l2voltState.add(double.parse(item["l2volt"]));
            l3voltState.add(double.parse(item["l3volt"]));

            l1akimState.add(double.parse(item["l1akim"]));
            l2akimState.add(double.parse(item["l2akim"]));
            l3akimState.add(double.parse(item["l3akim"]));
          }
        });
        if (this.mounted) {
          setState(() {
            loadingHttp = false;
          });
        }
      }
    });
    super.initState();
  }
 @override
  void dispose() {
    timerHttp.cancel();
    super.dispose();
  }

it gives this below error.

════════ Exception caught by widgets library ═══════════════════════════════════ The following assertion was thrown while finalizing the widget tree: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4263 pos 12: '_debugLifecycleState != _ElementLifecycle.defunct': is not true.

1

There are 1 best solutions below

1
On BEST ANSWER

this function disconnectFromServer(); was creating some error. And that error has effected the timer.

@override
void dispose() {
   disconnectFromServer();
   timerHttp.cancel();
   super.dispose();
}

I solved this problem by changing this function place. like this below.

@override
void dispose() {
   timerHttp.cancel();
   disconnectFromServer();
   super.dispose();
}