我有一个倒数计时器的秒表。
当列表中的第一个倒数结束时,我要开始下一个倒数,依此类推。
我怎样才能做到这一点?
谢谢!
我的代码到现在为止
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:timer_count_down/timer_controller.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.dark,
home: Ex(),
);
}
}
class Ex extends StatefulWidget {
@override
State<StatefulWidget> createState() => ExpandableListView();
}
class ExpandableListView extends State<Ex> {
final CountdownController controller = CountdownController();
List<int> list = [3, 4, 5, 6];
Timer _timer;
int counter = 3;
void _startTimer(seconds) {
if (_timer != null) {
_timer.cancel();
}
_timer = Timer.periodic(Duration(hours:0, minutes: 0, seconds: seconds), (timer) {
setState(() {
if (counter > 0) {
counter--;
} else {
_timer.cancel();
}
});
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
height: 500,
width: 200,
child: Column(
children: [
Container(
height: 200,
width: 200,
child: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Text(list[index].toString());
},
),
),
RaisedButton(
onPressed: () {
setState(() {
_startTimer(list[0]);
});
},
),
],
),
),
);
}
}
最佳答案
这样的一种方法就是这样。
class _MyWidgetState extends State<MyWidget> {
List<int> list = [3, 4, 5, 6];
Timer _timer;
int currentIndex = 0; //<-- to track which timer is running at the moment
void _startTimer() {
_timer = Timer.periodic(Duration(seconds: 1), (_) {
setState(() {
if (list[currentIndex] > 0) {
list[currentIndex]--;
} else {
if (currentIndex != (list.length - 1)) {
currentIndex++;
list[currentIndex]--;
}
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Text('${list[index]}');
},
),
),
RaisedButton(
child: Text('Start'),
onPressed: _startTimer,
),
],
),
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
}
链接到dartpad上的演示-https://dartpad.dev/ca29e0b73e1d919d941e113174b747cf要在完成后删除计时器,您可以这样做。
itemBuilder: (context, index) {
if(list[index] == 0){
return const SizedBox();
}
else{
return Text('${list[index]}');
}
}