NoSuchMethodError: The getter 'length' was called on null

Faris Azam picture Faris Azam · Jun 24, 2018 · Viewed 17.8k times · Source

So currently I'm building apps with Flutter which's still new to me, and I'm stuck at that exception in that title.

The problem is when I tried to call "widget.usernames.length" at ListView.builder, it would return that exception if it's null and no exception when there's data.

What I'm trying to accomplish is the get Length function should return null or 0 value so that the ListView would display nothing when there's no data.

return new Expanded(
  child: ListView.builder(
      padding: new EdgeInsets.all(8.0),
      itemExtent: 20.0,
      itemCount: widget.usernames.length,
      itemBuilder: (BuildContext context, int index){
        return Text("Bank ${widget.usernames[index] ?? " "}");
      }
  ),
);

I already tried

itemCount: widget.usernames.length ?? 0

but still no success.

EDIT**

Thanks to Jeroen Heier this code working well.

var getUsernameLength = 0 ;
if(widget.usernames == null){
  return getUsernameLength;
}else{
  return widget.usernames.length;
}

Answer

Jeroen Heier picture Jeroen Heier · Jun 24, 2018

If you use constructions like "widget.usernames.length" the programming code can fail on two places:

  • when widget = null
  • when widget.username = null (your situation)

You cannot call methods and properties on null-objects; that is why you get this error. So before you call widget.usernames.length you must be sure that both situations cannot occur. How this is done and if the check is really necessary depends on the rest of your program. One way to check is:

  return widget?.username?.length ?? 0;