Whenever your app interacts with an API to add, fetch, update, or delete any data it is essential to show a loader. It is essential because there may be some delay in response from the server in that case user needs to wait until the request is completed. In that case, displaying progress loaders during API Calls is important. In flutter, we can achieve easily.
You must have created a screen with a button. That will be used to create an API call. Here is a button we have on our screen. You can style the button as you would like. You can learn about a complete setup guide for a theme in Flutter.
FilledButton(
style: FilledButton.styleFrom(
// minimumSize: Size(200, 50),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5),
),
),
),
onPressed: () {
_submitForm(context);
},
child: const Text(
'Submit',
),
),
Now we need to work on the _submitForm method. Where we will be managing the API calling and the loader.
Future<void> _submitForm(BuildContext context) async {
final isValid = _formKey.currentState!.validate();
if (!isValid) {
return;
}
_formKey.currentState!.save();
setState(() {
_isLoading = true;
});
BuildContext? popupContext;
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
popupContext = context;
return Dialog(
child: Container(
color: Theme.of(context).colorScheme.background,
padding: const EdgeInsets.all(
AppSizes.spacingMedium,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(
height: AppSizes.spacingMedium,
),
CircularProgressIndicatorClass.circularProgressIndicator(
context),
const SizedBox(height: AppSizes.spacingWide),
SizedBox(
width: MediaQuery.of(context).size.width / 2.5,
child: const Center(
child: Text(
"Please wait while we process your request.",
softWrap: true,
),
),
),
const SizedBox(
height: AppSizes.spacingMedium,
),
],
),
),
);
},
);
final apiResponse = await AuthService().createAccount(requestParam); // Here you perform your api calling part.
if (popupContext != null && popupContext!.mounted) {
Navigator.of(popupContext!).pop();
}
}
It is a quick and easy solution to display progress loaders during API Calls in Flutter. However, there can be other approaches such as using a Stack widget. You can use the Stack widget and wrap your loader and screen content in the stack. Based on state management you can show the loader widget on the stack.