在运行异步任务时,我试图显示循环进度指示器。异步任务是通过单击按钮触发的,并且还会将用户定向到新页面。代码如下:
child: GestureDetector(
onTap: () async{
//some async task that takes a few seconds
Navigator.push( ...
}
我希望用户,当他单击按钮时首先看到一个圆形进度指示器,并且当任务完成时,应将他定向到另一个屏幕。但是我不知道如何向他显示此进度指示器。 预先感谢您的答复!
答案 0 :(得分:0)
您可以使用此库https://pub.dev/packages/simpleprogressdialog
创建一个ProgressDialog对象
ProgressDialog progressDialog = ProgressDialog(context: context, barrierDismissible: false);
然后在异步任务之前调用showMaterial
progressDialog.showMaterial(layout: MaterialProgressDialogLayout.overlayWithCircularProgressIndicator);
然后在执行异步任务后,关闭对话框。
progressDialog.dismiss();
答案 1 :(得分:0)
我对您想要的内容做了一些模拟:
检查以下代码:
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
// boolean variable to decide when to show progress indicator
bool showProgress = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: InkWell(
onTap: () async {
// set the progress indicator to true so it will be visible
setState(() {
showProgress = true;
});
// perform asynchronous task here
await Future.delayed(Duration(seconds: 4), null);
setState(() {
// set the progress indicator to true so it would not be visible
showProgress = false;
// navigate to your desired page
Navigator.push(context,
MaterialPageRoute(builder: (context) => AnotherScreen()));
});
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Your widgets can stay here',
style: TextStyle(fontSize: 20),
),
SizedBox(
height: 20,
),
Container(
height: 50,
width: 50,
color: Colors.blue,
child: Center(
// use ternary operator to decide when to show progress indicator
child: showProgress
? CircularProgressIndicator()
: Text('Tap me'),
),
),
],
),
),
),
);
}
}
检查以下输出:
注意:为了简单起见(使用了上面的示例)。为了避免多次调用setState
。您可以使用诸如Bloc或Provider之类的状态管理技术,并可能决定使用服务定位器进行注入。