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;
}
If you use constructions like "widget.usernames.length" the programming code can fail on two places:
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;