【问题标题】:the operand can't be null操作数不能为空
【发布时间】:2021-09-20 02:06:03
【问题描述】:

这个条件:

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

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

【问题讨论】:

  • 告诉我们你在哪里更新searchResultsFuture

标签: flutter dart google-cloud-firestore


【解决方案1】:

所以原因是变量被声明为late 实例化。这是一个很好的帖子/参考,用于了解 late variables 是否已被初始化。

在您的情况下(请参阅文档参考)

因为类型检查器无法分析字段和顶层的使用 变量,它有一个保守的规则,即不可为空的字段必须 在声明时(或在构造函数中初始化 实例字段的初始化列表)。所以 Dart 报告了一个编译 此类错误。

解决方案:

您可以通过使字段为空然后使用 null 来修复错误 断言运算符的用途:

你有两个选择。

首先,(假设您正在扩展 Stateful 小部件),您可以使用以下命令覆盖 initState() 函数:

  @override
  void initState() {
    // TODO: implement initState
    super.initState(); // this must always be first
    searchResultsFuture = //insert you future here
  }

或者,您可以通过将 Future 声明为可空来使用空安全实现:

Future<QuerySnapshot>? searchResultsFuture;

【讨论】:

  • 非常感谢!将 Future 声明为可以为空的工作。我还在学习,但我找错地方了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2021-09-28
  • 1970-01-01
  • 2017-12-21
  • 2011-05-19
相关资源
最近更新 更多