flutter - 操作数不能为空
问题描述
这个条件:
@override
Widget build(context) {
return Scaffold(
appBar: buildSearchField(),
body:
searchResultsFuture == null ? buildNoCont() : buildSearchRes(),
);}}
抛出此错误:
The operand can't be null, so the condition is always false.
Try removing the condition, an enclosing condition, or the whole conditional statement.
它是这样声明的:
late Future<QuerySnapshot> searchResultsFuture;
我已经在导入 cloud_firestore 包了。
我已经尝试了所有可用的方法,但仍然出现此错误,我需要保持这种状态。
解决方案
所以原因是变量被声明为延迟实例化。这是一个很好的帖子/参考,用于了解是否已初始化后期变量。
在您的情况下(请参阅文档参考)
因为类型检查器无法分析字段和顶级变量的使用,所以它有一个保守的规则,即不可为空的字段必须在其声明时(或在实例字段的构造函数初始化列表中)进行初始化。所以 Dart 报告这个类的编译错误。
解决方案:
您可以通过使该字段为空,然后在用途上使用空断言运算符来修复错误:
您有 2 个选项。
首先,(假设您正在扩展一个有状态的小部件),您可以使用以下命令覆盖initState()函数:
@override
void initState() {
// TODO: implement initState
super.initState(); // this must always be first
searchResultsFuture = //insert you future here
}
或者,您可以通过将 Future 声明为可为空来使用空安全实现:
Future<QuerySnapshot>? searchResultsFuture;
推荐阅读
- javascript - 简单的 SQL 到 PHP 数字增量动画 [Jquery]
- java - Android TCP 套接字不接收数据
- c# - 插值字符串格式问题
- angular - router-outlet 正在附加而不是替换 Angular 6.0.3
- opencv - 关于 RGB 和 CIELAB 之间转换的说明
- javascript - 这个增量重试代码是如何工作的?
- python - 舍入函数不是舍入?
- google-apps-script - 在 Google 表格中,使用脚本从图像中创建可点击的超链接
- apache-kafka - kafka 流 ktable 数据丢失
- c# - 使用 PostgreSQL 在 LINQ C# 上按列获取最后一行分组