【问题标题】:Flutter: Why renaming "MyApp" symbol to "Timer" in visual studio code generates errorsFlutter:为什么在 Visual Studio 代码中将“MyApp”符号重命名为“Timer”会产生错误
【发布时间】:2021-04-28 09:16:43
【问题描述】:

我正在使用颤振代码实现简单的计时器应用程序,但更改名称会产生 4 个错误,错误消息如下:

  1. 未使用的导入:'dart:async'。\n尝试删除导入指令。
  2. 没有为“Timer”类型定义方法“cancel”。\n尝试将名称更正为现有方法的名称,或定义一个名为“cancel”的方法。
  3. 没有为“Timer”类型定义方法“periodic”。\n尝试将名称更正为现有方法的名称,或定义一个名为“periodic”的方法。
  4. 没有为“Timer”类型定义方法“cancel”。\n尝试将名称更正为现有方法的名称,或定义一个名为“cancel”的方法。

我的代码如下:

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"),
            ),
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter timer


    【解决方案1】:

    在“dart:async”中已经存在一个名为“Timer”的类。 当您导入它时,您不能有两个具有相同名称的类。 因为它是一个抽象类 vs 代码希望你重写这些方法。

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 1970-01-01
      • 2012-01-03
      • 2015-05-10
      • 2018-04-19
      • 2017-12-04
      • 2020-10-14
      • 2016-03-29
      相关资源
      最近更新 更多