Flutter中如何关闭AlertDialog

3
我有一个简单的Flutter应用程序,其中包含从Firebase数据库(Cloud Firestore)加载的项目列表。
如您所见-有一个用于添加项目的按钮,每个项目都可以删除或编辑。当我按下所选项目的编辑按钮时,将显示带有TextField的AlertDialog,在此TextField中,用户可以查看当前项目名称并对其进行编辑。在编辑后,我仅遇到解除对话框的问题。请参考下图: enter image description here
   new IconButton(
      icon: new Icon(Icons.edit, color: Colors.white),
      onPressed: (){ showItemUpdateDialog(context, document); }
   )
   .......


void showItemUpdateDialog(BuildContext context, DocumentSnapshot item) {

  String itemName = "";
  var textContoller = new TextEditingController();
  textContoller.text = item['name'];

  var dialog = new AlertDialog(
    title: new Text("item name"),
    content: new TextField(
      controller: textContoller,
      onChanged: (value) {newName = value;},
    ),
    actions: <Widget>[
      new FlatButton(
        child: Text("cancel"),
        onPressed: (){
          Navigator.pop(context);
        },
      ),
      new FlatButton(
          child: Text("Update"),
          onPressed: () { 
            updateItemOnServer(item, newName); 
            Navigator.pop(context); 
          }
      )
    ],
  );

  showDialog(context: context, child: dialog);
}

值正在正确更新,但AlertDialog没有被关闭。以下是错误代码。我认为这是由于调用了已从服务器修改和更新的项目。

flutter:在处理手势时引发了以下断言: flutter:查找已停用小部件的祖先是不安全的。 flutter:此时小部件元素树的状态不再稳定。要在其dispose()方法中安全地引用flutter:widget的祖先,请通过在小部件的didChangeDependencies()方法中调用flutter:inheritFromWidgetOfExactType()来保存祖先的引用。


你解决了吗?如果解决了,怎么做的? - dragonfly02
你好 @moonvader,能帮我一下吗?我想要实现和你这里一样的功能。这是我的问题链接:https://stackoverflow.com/questions/61092208/edit-listview-item-in-flutter-on-edit-click-using-dialog - Jaspalsinh Gohil
3个回答

13

试试这个,

 Navigator.of(context, rootNavigator: true).pop(),

谢谢您!我的应用程序中有多个导航器,我无法弄清楚为什么其他答案都对我无效。 - skit456
@shanmugavel-gk,您能否解释一下为什么这个可以工作? - Jatin Lalwani
从文档中得知:如果将rootNavigator设置为true,则会返回此类的最远实例的状态。这对于将内容推送到Navigator的所有后续实例之上非常有用。 - RobDil

6

使用最新的Flutter技术:

Navigator.of(context).pop();

替代

标签

的方法
Navigator.pop(context);

当从堆栈中弹出Dialog时,出现了两次的情况。如果这个解决方案能够解决问题,请告诉我!


1
尝试这个:
Navigator.popUntil(context, ModalRoute.withName('/login'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接