Flutter:失败的断言:布尔表达式不能为空

时间:2020-07-13 10:52:59

标签: flutter dart null future

在扑朔迷离中,我使用Future从Firestore云数据库中调用一个值,然后尝试将此值分配给变量。

这是我的代码:

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);
        });
  }
}

但是我在使用将来的构建器时遇到错误-Another exception was thrown: Failed assertion: boolean expression must not be null

问题出在哪里。以及我该如何解决?

1 个答案:

答案 0 :(得分:2)

问题出在FutureBuilder代码中。要检查data是否到达,您正在检查错误的标志。选中snapshot.hasData而不是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
              }
            });
      }