我在创建学习 Todo 应用程序时遇到了奇怪的问题。我实现了 TaskList 类和 TaskTile 类,如下所示。
任务列表类如下
import 'package:provider/provider.dart';
import 'package:todoey/Models/taskdata.dart';
import 'package:todoey/widgets/task_tile.dart';
class TasksList extends StatefulWidget {
@override
State<TasksList> createState() => _TasksListState();
}
class _TasksListState extends State<TasksList> {
@override
Widget build(BuildContext context) {
return Consumer<TaskData>(builder: (context, taskData, child) {
return ListView.builder(
itemBuilder: (context, index) {
final task = taskData.taskList[index];
return TaskTile(
longPressCallBack: () {
taskData.deleteTask(task);
},
name: task.name,
isChecked: task.isDone,
checkBoxCallBack: (newValue) {
taskData.updateTask(task);
},
);
},
itemCount: taskData.taskList.length,
);
});
}
}
TaskTile 类如下
class TaskTile extends StatelessWidget {
final bool? isChecked;
final String name;
final Function checkBoxCallBack;
final Function longPressCallBack;
TaskTile(
{required this.name,
this.isChecked,
required this.checkBoxCallBack,
required this.longPressCallBack});
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(
name,
style: TextStyle(
decoration: isChecked! ? TextDecoration.lineThrough : null,
),
),
trailing: Checkbox(
fillColor: MaterialStateProperty.all(Colors.lightBlueAccent),
checkColor: Colors.white,
value: isChecked!,
onChanged: (newValue) {
checkBoxCallBack(newValue);
},
),
onLongPress: () => longPressCallBack,
);
}
}
现在的问题是它不调用父类的longPressCallBack,即TaskList 类。我进行了调试,它调用了 TaskTile 类的 onLongPress,但没有调用它的父类的回调,这就是 deleteTask 不起作用的原因。