Reputation: 3049
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 ?
Upvotes: 1
Views: 1508
Reputation: 5388
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
}
});
}
Upvotes: 3