獲取 JSON 時對空值錯誤使用的空檢查運算符

約翰

我不明白。

  builder: (context, snapshot) {
    if (snapshot.data != null && widget.stored!.b) {
      return new GridView.count(
          children: List.generate(snapshot.data!.length, (index) {
            return _buildCell(snapshot.data![index]);
          }));
    }
  });

所以,回顧一下:

if (snapshot.data != null && widget.stored!.b)

這個片段似乎是錯誤所在。我正在嘗試獲取 'b' 並僅顯示那些帖子(如果為真)。

我的 Stored.dart 中有這個:

class Stored extends Base {
  late bool b;
}

如您所見,我正在嘗試檢查字符串是否為“1”,如果是,則為其分配 true:

  Stored(Map<String, dynamic> json) : super(json) {
    post-number = json["posts"];
    bool b = post-number == "1";
}

JSON 響應為:

{"posts":"1"}';

我不明白我做錯了什麼?我試圖只顯示其中編號為 1 的帖子,但是在嘗試獲取時,Null check operator used on a null value出現錯誤。這是為什麼?

特里科特

錯誤意味著widget.storednull!告訴編譯器,它不應該是空。因此,請改用條件屬性訪問:

widget.stored?.b == true

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章