NoSuchMethodError: The getter 'length' was called on null

Far*_*zam 2 dart flutter

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

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

我想要完成的是get Length函数应该返回null或0值,以便ListView在没有数据时不显示任何内容。

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] ?? " "}");
      }
  ),
);
Run Code Online (Sandbox Code Playgroud)

我已经试过了

itemCount: widget.usernames.length ?? 0
Run Code Online (Sandbox Code Playgroud)

但仍然没有成功。

编辑**

感谢Jeroen Heier,此代码运行良好。

var getUsernameLength = 0 ;
if(widget.usernames == null){
  return getUsernameLength;
}else{
  return widget.usernames.length;
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*ier 5

如果您使用“ widget.usernames.length”之类的构造,则编程代码可能在两个地方失败:

  • 当部件= null
  • 当widget.username = null(您的情况)时

您不能在空对象上调用方法和属性。这就是为什么您会收到此错误。因此,在调用widget.usernames.length之前,必须确保两种情况均不会发生。如何完成以及是否确实需要检查取决于程序的其余部分。一种检查方法是:

  return widget?.username?.length ?? 0;
Run Code Online (Sandbox Code Playgroud)