Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchMethodError: The getter 'length' was called on null

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;
}
like image 477
Faris Azam Avatar asked Dec 19 '25 12:12

Faris Azam


1 Answers

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;
like image 104
Jeroen Heier Avatar answered Dec 22 '25 10:12

Jeroen Heier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!