当我从列表视图中删除项目时,尽管添加项目工作正常,但在颤振中重置删除项目下方的计时器。如何在删除项目上保持计时器状态? 示例:如果我删除项目 2,项目 0 和项目 1 的计时器仍保持其状态,但项目 3 的计时器重置为其原始值。 这是我的代码...
class MyListView extends StatefulWidget {
@override
_MyListViewState createState() => _MyListViewState();
}
class _MyListViewState extends State<MyListView> {
List<Todo> todos = [
Todo("120", "Item 0", 10),
Todo("121", "Item 1", 15),
Todo("122", "Item 2", 20),
];
// adding item on click add
void _addTodoItem() {
setState(() {
int index = todos.length;
todos.add(Todo("12$index", "Item $index", 30));
});
}
// build list view
Widget _buildTodoList() {
return new ListView.builder(
itemBuilder: (context, index) {
if (index < todos.length) {
return _buildTodoItem(todos[index], index);
} else
return null;
},
);
}
// build listview item
Widget _buildTodoItem(Todo todo, int index) {
return GestureDetector(
key: ValueKey(todo.key),
onTap: () => _removeTodoItem(index),
child: todo.text != null
? Row(
children: [
Text(todo.text),
SizedBox(
width: 20,
),
TimerWidget(
duration: todo.duration,
)
],
)
: Text("Loading Time"),
);
}
// remove item when click on list item
void _removeTodoItem(int index) {
setState(() => todos.removeAt(index));
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text('Todo List')),
body: _buildTodoList(),
floatingActionButton: new FloatingActionButton(
onPressed: _addTodoItem,
tooltip: 'Add task',
child: new Icon(Icons.add)),
);
}
}
我的计时器小工具
class _TimerWidgetState extends State<TimerWidget> {
Timer _timer;
int _start = 0;
@override
void initState() {
// TODO: implement initState
super.initState();
_start = widget.duration;
this.startTimer();
}
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
});
} else {
setState(() {
_start--;
});
}
},
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return Text("$_start");
}
}
Todo 模型
class Todo {
String key;
String text;
int duration;
Todo(key, text, duration) {
this.key = key;
this.text = text;
this.duration = duration;
}
}