dart - 空状态页面和导航器问题?

标签 dart flutter future flutter-navigation

我想实现 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/

相关文章:

android-studio - 如何在 flutter 中编写条件语句?

flutter - WebView显示空白页(我认为未加载)

使用 sqflite 时出现 flutter 错误,表中没有这样的列

flutter - 我应该使用//或///在 Dart 中进行评论吗?它会使应用程序变慢吗?

scala - 如何在 Actor 的接收方法中使用 Future 来处理容错?

c++ - 并发 TS:std::future<...>::then,如何在不存储返回的 future 的情况下保持链条事件?

dart - 使用 Barcode Scanner 中的值在 flutter 中添加新值后,列表不会扩展

dart - pubspec.yaml 中如何设置使用最新版本的包?

firebase - FLUTTER:如何在流构建器中使用导航器?

dart - Flutter:构造函数中List参数的默认赋值