Flutter Error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type

Flutter Error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type

我正在使用启用了空安全的新飞镖版本 <2.13.0-107.0.dev>。

有了这个任务列表:

  List<Task> tasks = [
    Task(name: 'find a way to live happy'),
    Task(name: 'Listen to music!!!'),
    Task(name: 'Live in the other world till ur power is off'),
  ];

当我尝试在这样的 ListView.builder 构造函数中使用它时:

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: tasks.length,
      itemBuilder: (context, index) {
         TaskTile(
          taskTitle: tasks[index].name,
          isChecked: tasks[index].isDone,
          checkboxCallback: (bool? checkboxState) {
            setState(() {

              tasks[index].toggleDone();
            });
          },
        );
      },
    );
  }

我收到这个错误:

错误:正文可能正常完成,导致 'null' 被 returned,但 return 类型可能不是- 可空类型。

运行 日志中出现此错误:

错误:必须 return 编辑非空值,因为 return 类型 'Widget' 不允许空值。

有关详细信息,任务 class 定义如下:

class Task {
  String name;
  bool isDone;

  Task({this.name = '', this.isDone = false});

  void toggleDone() {
    isDone = !isDone;
  }
}

您忘记在 itemBuilder 中使用 return

使用

ListView.builder(
  itemBuilder: (context, index) {
    return TaskTile(...); // <-- 'return' was missing 
  },
)

您不会返回 TaskTile 小部件:

return ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
     TaskTile(

应该是:

return ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
     return TaskTile(