Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using the new dart version <2.13.0-107.0.dev> with null safety enabled.

With this List of tasks:

  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'),
  ];

when I try to use it in a ListView.builder constructor like this:

  @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();
            });
          },
        );
      },
    );
  }

I get this error:

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

and this error in the Run log:

Error: A non-null value must be returned since the return type 'Widget' doesn't allow null.

For more info, the Task class is defined as follows:

class Task {
  String name;
  bool isDone;

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

  void toggleDone() {
    isDone = !isDone;
  }
}
like image 294
MadMax Avatar asked Mar 30 '21 15:03

MadMax


2 Answers

You forgot to use return in your itemBuilder.

Use

ListView.builder(
  itemBuilder: (context, index) {
    return TaskTile(...); // <-- 'return' was missing 
  },
)
like image 75
CopsOnRoad Avatar answered Oct 22 '22 06:10

CopsOnRoad


You are not returning the TaskTile widget:

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

should be:

return ListView.builder(
  itemCount: tasks.length,
  itemBuilder: (context, index) {
     return TaskTile(
like image 22
Patrick O'Hara Avatar answered Oct 22 '22 05:10

Patrick O'Hara