我想实现 empty state page在 Flutter 应用程序中,当新闻提要为空时。
当提要中没有事件时,我想显示“无事件”。当数据库有数据时,我想将其从 StreamBuilder
加载到 ListView.builder
我尝试使用:
child: StreamBuilder(
stream: collection.snapshots(),
builder: (context, snapshot) {
if(snapshot.hasData) {
return ListView.builder(
itemBuilder: (context, index) =>
build(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
} else {
return _emptyStateWidget();
}
我必须在 else 语句中返回一些东西,因为有时快照不会有数据,所以会抛出错误,Widget 返回 null。
但这会导致小部件树出现问题。因为如果我稍后尝试在 build
Widget 中使用 Navigator.push:
Widget build(BuildContext context, DocumentSnapshot document) {
…
FlatButton(
onPressed: () async {
await function(document);
if(validated == true) {
await Navigator.push(context, new MaterialPageRoute(
builder: (BuildContext context) =>
new Screen(documentInfo: documentInfo)));
}
抛出错误:
Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
有没有办法避免这种情况,从而不会抛出错误?
出于某种原因,如果我在 await function(document)
之前调用 Navigator.push
,则不会抛出任何错误。但我不能允许这样做,因为它必须先在功能中执行数据验证,并且只有在成功时才导航。
谢谢!
更新:
经过更多测试,我认为问题是由 StreamBuilder
引起的。每当收到新事件时它都会重建。因此,这会在调用 Navigator.push
时导致问题,并且它会收到新事件,因此请尝试重建。
如何解决?是否可以阻止 StreamBuilder
重建后代?
最佳答案
发生这种情况是因为您在构建小部件树时试图导航到其他地方。
您应该将 Navigation.push
移动到流监听器,例如,在您的 initState
中。
void initState() {
super.initState();
collection.snapshots.listen((data){
if(validated == true) {
await Navigator.push(context, new MaterialPageRoute(
builder: (BuildContext context) =>
new Screen(documentInfo: documentInfo)));
}
});
}
关于dart - 空状态页面和导航器问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902636/