1

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

Where is the problem. And How can I fix this ?

0

1 Answer 1

3

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
              }
            });
      }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.