在flutter中,我使用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
时遇到了一个错误
问题出在哪里。我该怎么解决这个问题
问题出在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
}
});
}