Flutter:失败的断言:布尔表达式不能为空 [英] Flutter: Failed assertion: boolean expression must not be null

查看:585
本文介绍了Flutter:失败的断言:布尔表达式不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在扑朔迷离中,我使用Future调用了Firestore云数据库中的一个值,并尝试将该值分配给变量。

In flutter, I call a value from Firestore cloud database by using future and try to assigning this value to a variable.


这是我的代码:

Here is my code:


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Gyanpothro extends StatefulWidget {
  @override
  _GyanpothroState createState() => _GyanpothroState();
}

class _GyanpothroState extends State<Gyanpothro> {
  Firestore db = Firestore.instance;
  Future databaseFuture;
  @override
  void initState() {
    databaseFuture = db.collection('notice').document('0').get();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: databaseFuture,
        builder: (context, snapshot) {
          if (!snapshot.data) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                LinearProgressIndicator(
                  backgroundColor: Colors.amber,
                ),
                Text("Loading"),
              ],
            );
          }
          var _notice = snapshot.data.data['notice'];
          var _heading = snapshot.data.data['heading'];
          print(_notice);

          return Text(_notice);
        });
  }
}

但是在使用以后的生成器时出现错误-引发了另一个异常:失败的断言:布尔表达式不能为空

But I get a error for using future builder - Another exception was thrown: Failed assertion: boolean expression must not be null

问题出在哪里。而我该如何解决呢?

推荐答案

问题出在 FutureBuilder 代码。要检查数据是否到达,请检查错误的标志。检查 snapshot.hasData 而不是 snapshot.data

The problem is in the FutureBuilder code. To check if the data has arrived, you are checking the wrong flag. Check snapshot.hasData instead of snapshot.data

    @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: databaseFuture,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                // Data is avialable. call snapshot.data 
              }
              else if(snapshot.hasError){     
                 // Do error handling
              }
              else {
                // Still Loading. Show progressbar
              }
            });
      }

这篇关于Flutter:失败的断言:布尔表达式不能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆