英文:
How to fetch the data from REST API inside ListView.builder() in flutter?
问题
以下是已翻译的内容:
"我是Flutter的新手,尝试从REST API获取数据,但出现错误 _CastError (Null check operator used on a null value).
List<User>? user;
child: ListView.builder(
itemCount: user?.length,
itemBuilder: ((context, index) {
return Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: [Text(user![index].firstName)],
),
);
}),
),
在这里,我对一个为null
的变量执行操作。我已经定义了itemCount: user?.length
和Text(user![index].firstName)
来处理这个问题,但我得到了这样的错误
如何修复这个问题?"
英文:
I'm new to Flutter and trying to fetch the data from the REST API but get the error _CastError (Null check operator used on a null value).
List<User>? user;
child: ListView.builder(
itemCount: user?.length,
itemBuilder: ((context, index) {
return Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: [Text(user![index].firstName)],
),
);
}),
),
here I performing an operation on a variable that is null
. I have defined itemCount: user?.length
and Text(user![index].firstName)
to handle this but I get error like this
how to fix this?
答案1
得分: 1
itemCount: user?.length
操作符 ?. 表示如果 user 为 null,则返回长度或 null;如果 itemCount 为 null,则会一直构建直到 itemBuilder 也返回 null。
user![index].firstName
这表示你确信 user 不为 null,因此 index 会返回一个非 null 值。这是一个矛盾,因为在 counter 中你不确定是否为 null,但在 builder 中你确定不为 null:
ListView.builder(
itemCount: user?.length ?? 0, /// 这告诉 builder 如果 user 为 null,则没有项目,因此 itemBuilder 不会迭代
itemBuilder: (context, index) {
....
},
);
现在不会报错,但在修复 user 变量以不为 null 之前,它将为空。
英文:
itemCount: user?.length
the operatnd ?. means that it will return the length or null if user is null, if itemCount is null it will build infinity until the itemBuilder returns null too.
user![index].firstName
It means that you're sure user is not null and by doing that the index will return a not null value. This is a contradiction because you're not sure if its null in the cunter, but you're sure that is not in the builder:
ListView.builder(
itemCount: user?.length ?? 0, ///This tells the builder there are no items in case the user is null, so itemBuilder will not iterate
itemBuilder: (context, index) {
....
},
);
Now it will not report an error, but it will be empty until you fix your user variable to not be null.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论