Reputation: 639
I am trying to show a circular progress indicator, while I run an async task. The async task is triggered by a button click and is also directing the user to a new page. The code looks like this:
child: GestureDetector(
onTap: () async{
//some async task that takes a few seconds
Navigator.push( ...
}
I want the user, when he clicks the button to first see a circular progress indicator and when the task is complete he should be directed to another screen. But I have no idea how to show him this progress indicator. Thanks for your answers in advance!
Upvotes: 4
Views: 4519
Reputation: 14043
I made a little simulation of what you want:
Check the code below:
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'),
),
),
],
),
),
),
);
}
}
Check output below:
NOTE: For the sake of simplicity(the example above was used). To avoid calling setState
multiple times. You can use a state management technique like Bloc or Provider and maybe decide to make use of a service locator for injection.
Upvotes: 2
Reputation: 12673
You can use this library https://pub.dev/packages/simpleprogressdialog
Create an object of ProgressDialog
ProgressDialog progressDialog = ProgressDialog(context: context, barrierDismissible: false);
Then invoke showMaterial
before your async task
progressDialog.showMaterial(layout: MaterialProgressDialogLayout.overlayWithCircularProgressIndicator);
Then after the async task, dismiss the dialog.
progressDialog.dismiss();
Upvotes: 1