如何解决从另一个独立于调用树的有状态小部件触发包含 setState() 的方法
我有一个列出几个文件的主页。在 initState 函数中,它将异步加载文件,然后构建列表。
每个文件都带有一个调用 Stateful ModalSheet 对象的 more 按钮,上面有几个 Stateful sheetButton 对象。按下后,这些按钮会弹出模态表并推送一个带有一些 alertDialog 的新对话框。用户可以单击与 alertDialog 相关联的操作按钮,然后弹出它自己并基本上返回到默认主页。我的目标是当且仅当用户单击 alertDialog 中的操作按钮之一时,主页才会刷新自身(触发具有某些 setState 的方法)。
由于sheetButton弹出ModalSheet时调用树被一分为二,所有从父主页面使用.then()的努力都失败了,then()只接收到modalsheet的返回值,而不是工作表按钮。
我也尝试过使用全局密钥,尽管它是一个样板解决方案。但是无论我如何在主页面中设置它,key.currentState 和 currentContext 都保持空值,因为我在 initstate、build 和传入键的小部件中打印它们。因此所有的 key.currentState.method( ) 调用也为 null。
我也尝试过使用通知。我创建了自己的通知类,并在主页的根目录添加了一个具有我独特类型的通知侦听器。但是,无论我如何在单击警报对话框操作按钮时在我的 sheetButton 类中发送相同的通知类型,侦听器都不会收到任何通知。原因也可能是因为我在网上阅读了其他类似问题,sheetButton 和主页不在同一上下文或同一棵树中。
在这一点上,我完全没有资源。这个任务看起来很简单,但我就是找不到解决方案。
class DataPage extends StatefulWidget {
@override
_DataPageState createState() => _DataPageState();
}
class _DataPageState extends State<DataPage> {
void initState() {
loadData(); //it has to use this method since it has setState in it
}
Widget build(BuildContext context) {
//somewhere inside scaffold
onpressed(){
showModalBottomSheet(
context: context,isScrollControlled: true,//here the builder is using my own BottomSheetWidget class,but
//it is trivial
builder: (context) => BottomSheetWidget(files[index],Metas[index])
);// I tried using .then() here,it does get the Future value back,//but only up til the point where the sheetbutton pops the sheet,//making it impossible to the get the result from alertDialog actions.
}
}
class SheetButton extends StatefulWidget {
}
class _SheetButtonState extends State<SheetButton> {
@override
Widget build(BuildContext context) {
return MaterialButton(
onpressed: () {
Navigator.pop(context); // here,the sheetButton pops the modalSheet,breaking the
//call tree and making everything complicated,//the use case needs the modal sheet disappear before making doing new actions with the dialog.
if(widget.text == "Info"){
showDialog(
context: context,builder: (BuildContext context) {
return AlertDialog(
actions: <Widget>[
new FlatButton(
child: new Text("Submit"),onpressed: () {
//I tried sending stuff here
Navigator.of(context).pop();
},),],);
});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。