Leo*_*hiu 2 showdialog flutter
在 Flutter 中,我使用 FutureBuilder 来显示来自 API 的数据。我想在出现错误时弹出一个错误对话框。
但是,当我调用 showDialog() 时,它会抛出错误
setState() or markNeedsBuild() called during build.
Run Code Online (Sandbox Code Playgroud)
这是我的代码
return FutureBuilder(
future: xxx,
builder: (context, snapshot) {
if (snapshot.hasData) {
//DO SOMETHING
} else if (snapshot.hasError) {
//TODO: Show Error
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text("HAHAHA"),
actions: <Widget>[
FlatButton(
child: Text("No"),
),
FlatButton(
child: Text("Yes")
),
],
);
}
);
return Container();
} else {
//DO SOMETHING
}
},
Run Code Online (Sandbox Code Playgroud)
请帮助建议我如何在 FutureBuilder 中显示对话框。
当 build 方法正在构建小部件时,我们不能调用 setState、navigate 或 showDialog。因此,我们可以等待一微秒,同时构建方法完成构建小部件,这样我们就可以显示对话框。
创建如下方法。
showError() async {
await Future.delayed(Duration(microseconds: 1));
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text("HAHAHA"),
actions: <Widget>[
FlatButton(
child: Text("No"),
),
FlatButton(child: Text("Yes")),
],
);
});
}
Run Code Online (Sandbox Code Playgroud)
并在您想要显示对话框的地方调用此方法。
| 归档时间: |
|
| 查看次数: |
4870 次 |
| 最近记录: |