Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter "periodic" method is not defined

It says "periodic method is not defined" when I try to use the "Timer.periodic" method. Here is that part of the code and image of error message I get:

import 'dart:async';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int timeLeft = 5;

  void _startCountDown() {
    Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        timeLeft--;
      });
    });
  }
}

Error Message

I write accordingly to the document but I get the error anyway. How can I use this method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have this error because you have a class named Timer in your code, or from one of your imports (other than dart:async). You can fix it by renaming your own Timer class to something else, or using the hide keyword from the import that has the Timer class.

For example, if you have an import from a package abc that has the Timer class, you can hide it this way:

import 'package:abc/abc.dart' hide Timer;

In VSCode, you can Ctrl+click on Timer to determine where that Timer class came from.


Alternatively, you can prefix your dart:async import:

import 'dart:async' as da;

And now you can use Timer like this:

da.Timer.periodic(...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading