首页 > 解决方案 > 操作数不能为空

问题描述

这个条件:

@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 包了。

我已经尝试了所有可用的方法,但仍然出现此错误,我需要保持这种状态。

标签: flutterdartgoogle-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;

推荐阅读