【发布时间】:2021-04-28 09:16:43
【问题描述】:
我正在使用颤振代码实现简单的计时器应用程序,但更改名称会产生 4 个错误,错误消息如下:
- 未使用的导入:'dart:async'。\n尝试删除导入指令。
- 没有为“Timer”类型定义方法“cancel”。\n尝试将名称更正为现有方法的名称,或定义一个名为“cancel”的方法。
- 没有为“Timer”类型定义方法“periodic”。\n尝试将名称更正为现有方法的名称,或定义一个名为“periodic”的方法。
- 没有为“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"),
),
],
),
),
);
}
}
【问题讨论】: