Flutter: Why renaming "MyApp" symbol to "Timer" in visual studio code generates errors

Viewed 122

I'm implementing simple timer app using flutter code but changing name creating 4 errors, error messages are as follow:

  1. Unused import: 'dart:async'.\nTry removing the import directive.
  2. The method 'cancel' isn't defined for the type 'Timer'.\nTry correcting the name to the name of an existing method, or defining a method named 'cancel'.
  3. The method 'periodic' isn't defined for the type 'Timer'.\nTry correcting the name to the name of an existing method, or defining a method named 'periodic'.
  4. The method 'cancel' isn't defined for the type 'Timer'.\nTry correcting the name to the name of an existing method, or defining a method named 'cancel'.

My code is bellow:

import 'dart:async';
import 'package:flutter/material.dart';

void main() => runApp(MyApp()); //change MyApp to Timer

class MyApp extends StatelessWidget { //change MyApp to Timer
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 10;
  Timer _timer;

  void _startTimer() {
    _counter = 10;
    if (_timer != null) {
      _timer.cancel();
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_counter > 0) {
          _counter--;
        } else {
          _timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Timer App"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            (_counter > 0)
                ? Text("")
                : Text(
                    "DONE!",
                    style: TextStyle(
                      color: Colors.green,
                      fontWeight: FontWeight.bold,
                      fontSize: 48,
                    ),
                  ),
            Text(
              '$_counter',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 48,
              ),
            ),
            RaisedButton(
              onPressed: () => _startTimer(),
              child: Text("Start 10 second count down"),
            ),
          ],
        ),
      ),
    );
  }
}

1 Answers

In 'dart:async' already exists a class named "Timer". As you are importing this, you can't have two classes with the same name. Because it's an abstract class vs code wants you to override those methods.

Related