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--;
});
});
}
}
I write accordingly to the document but I get the error anyway. How can I use this method?
>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(...)