在Flutter中使用streamBuilder时条件不起作用 [英] Condition does not work when using a streamBuilder in Flutter
问题描述
我正在尝试实现一个屏幕,该屏幕显示Firebase中的数据,但我希望 streambuilder
检查数据库是否为空,如果数据库为空,我希望它显示一个文本,显示否".数据"但如果不是,我希望它显示Firebase中的数据.
I'm trying to implement a screen that displays data from Firebase but I want the streambuilder
to check if the database is empty, if it's empty I want it to show a text saying "no data" but if it's not, I want it to show the data from firebase.
这是我拥有的代码,但是无法按预期工作,它在没有数据的情况下仅向我显示一个空白屏幕(当我在数据库中有数据时,它可以很好地工作,我只是不想让用户没有数据时,将看到黑屏).您能告诉我这段代码有什么问题吗?最好的方法是什么?
This is the code I have but it does not work as expected, it just shows me a blank screen when there is no data(it works fine when I have data in the database, I just don't want the user to see a blank screen when there is no data). Can you advise what is wrong with this code? what is the best way to implement this?
@override
Widget build(BuildContext context) {
double height = responsive.height(context);
double width = responsive.width(context);
var stream = Firestore.instance
.collection('favoritePost')
.document(widget.currentUserId)
.collection('favoritePost')
.orderBy('timestamp', descending: true)
.snapshots();
return Scaffold(
backgroundColor: kBackgroundColorForAllScreens,
appBar: PreferredSize(
preferredSize: Size.fromHeight(responsive.height(context) / 20),
child: SimpleAppBar(
label: 'Tus Favoritos',
witdh: responsive.width(context) / 4.7,
onPressed: () {
Navigator.pop(context);
},
),
),
body: Column(
children: <Widget>[
Expanded(
child: Container(
child: StreamBuilder(
stream: stream,
builder: (context, snapshotPost) {
if (snapshotPost.hasData) {
return ListView.builder(
itemExtent: height / 3.3,
itemCount: snapshotPost.data.documents.length,
itemBuilder: (BuildContext context, int index) {
Reviews reviews = Reviews.fromDoc(
snapshotPost.data.documents[index],
);
Provider.of<UserData>(context).reviews = reviews;
return ReviewsMenu(
reviews: reviews,
user: widget.user,
currentUserId: widget.currentUserId,
showDialogForDelete: true,
comingFromFavorite: true,
);
},
);
} else {
return Center(
child: Text('NO DATA'),
);
}
},
),
),
),
],
),
);
}
推荐答案
不要在构建方法中初始化流
Dont initialize streams in build method
使用 StatefulWidget
并在 State.initState
// inside, class [...] extends State<[...]>
Stream stream;
@override
void initState() {
super.initState();
stream = Firestore.instance
.collection('favoritePost')
.document(widget.currentUserId)
.collection('favoritePost')
.orderBy('timestamp', descending: true)
.snapshots();
}
在 StreamBuilder.builder
内部,其中 Snapshot.hasData
检查评论数是否大于0
inside StreamBuilder.builder
where Snapshot.hasData
check if the number of reviews are greater then 0
if (snapshot.hasData) {
if (snapshot.data.documents.length == 0) {
return Center(child: Text('NO DATA'));
}
}
然后照常使用它
这篇关于在Flutter中使用streamBuilder时条件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!