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

29,129

Solution 1

You forgot to use return in your itemBuilder.

Use

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

Solution 2

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(
Share:
29,129

Related videos on Youtube

MadMax
Author by

MadMax

Updated on July 09, 2022

Comments

  • MadMax
    MadMax 5 months

    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;
      }
    }
    
  • MadMax
    MadMax over 1 year
    Poor me !!! what I was missing, OMG!!! The thing is that since they added the null safety, many errors come out every time, and for that reason I get so confused. Maybe when I get used to null safety I may get more comfortable in reading the errors. Also I think the error description provided by Dart was misleading for me, it didn't get straight through the point IMO. Thank you so much @copsonroad
  • MadMax
    MadMax over 1 year
    That was descriptive, I'd be careful next time and learn from this mistake , it really took my time and a lot of search but it didn't work for me, hence the error was so silly. @patrick-ohara Thank you;

Related