Home > Back-end >  What's wrong with the .cancel() method in flutter
What's wrong with the .cancel() method in flutter

Time:12-25

I've always use the .cancel() method after import dart.async in flutter but when I want to use it in this project I got an error, flutter don't recognize it, if somoene can help I will be really greatful have a nice day.

import 'package:flutter/material.dart';
import 'dart:async';
class Timer extends StatefulWidget {
  const Timer({Key? key}) : super(key: key);

  @override
  _TimerState createState() => _TimerState();
}

class _TimerState extends State<Timer> {
  int _seconds = 0;
  int _minutes = 25;

   late Timer _timer;
   void _startTimer(){
     if (_timer!= null){
       _timer.cancel();
     }

   }

  @override

CodePudding user response:

late Timer _timer; is referring to the widget class instead of Timer class. Rename Timer widget with something else

class TimerWidget extends StatefulWidget {
  TimerWidget({Key? key}) : super(key: key);

  @override
  _TimerWidgetState createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  late Timer _timer;
  void _startTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
//......
  • Related