问题
I keep getting a slight null error before displaying my items. Please can I get help on the best way to use streambuilder without encountering any error?
回答1:
Use ConnectionState:
StreamBuilder(
stream: Firestore.instance.collection('stores').document(currentUserUID).snapshots(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(8.0),
title: Text(snapshot.data.data["about"]),
leading: Text(
snapshot.data.data["location"],
));
});
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
),
https://api.flutter.dev/flutter/widgets/ConnectionState-class.html
回答2:
StreamBuilder<QuerySnapshot>(
stream:
Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError)
return Center(child:Text('${snapshot.error.toString()}'));
if (snapshot.hasData) {
final List<DocumentSnapshot> documents = snapshot
.data.documents;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (context, index) => RestaurantCard(
documents[index].documentID,
name: documents[index].data['name'],
address: documents[index].data['address'],
image: documents[index].data['photo'],
),
scrollDirection: Axis.horizontal,
);
} else {
return Center(child: CircularProgressIndicator());
}
},
)
来源:https://stackoverflow.com/questions/61698823/i-keep-getting-a-slight-null-error-when-using-stream-builder-in-flutter