Alf*_*ulo 3 dart firebase flutter stream-builder
我正在尝试实现一个显示来自 Firebase 的数据的屏幕,但我想streambuilder检查数据库是否为空,如果为空,我希望它显示一个文本,上面写着“无数据”,但如果不是,我希望它显示来自 firebase 的数据。
这是我拥有的代码,但它没有按预期工作,它只是在没有数据时向我显示一个空白屏幕(当我在数据库中有数据时它工作正常,我只是不希望用户看到一个空白没有数据时的屏幕)。你能告诉我这段代码有什么问题吗?实现这一点的最佳方法是什么?
@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'),
);
}
},
),
),
),
],
),
);
}
Run Code Online (Sandbox Code Playgroud)
不要在构建方法中初始化流
使用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();
}
Run Code Online (Sandbox Code Playgroud)
在StreamBuilder.builderwhereSnapshot.hasData检查评论数量是否大于 0
if (snapshot.hasData) {
if (snapshot.data.documents.length == 0) {
return Center(child: Text('NO DATA'));
}
}
Run Code Online (Sandbox Code Playgroud)
然后像你已经拥有的那样正常使用它
| 归档时间: |
|
| 查看次数: |
1452 次 |
| 最近记录: |