Flutter: Timer can not stop

爱⌒轻易说出口 提交于 2021-01-07 01:31:31

问题


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:


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


来源:https://stackoverflow.com/questions/65300728/flutter-timer-can-not-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!