Flutter loading indicator before showDialog

Viewed 418

I have a button, that runs showDialog. Is it possible to make some loading indicator before this dialog opened?

I have web application. When I press "details" button, It gets data from backend and then process them and then show this data in showDialog. While it process them i want to make some loading indicator, because dialog waits untill all data will be collected.

1 Answers

If you are making a call to your backend I suppose that you are performing an asynchronous operation which means that you should be able to use then():

Code Sample

class MyDetailsButton extends StatefulWidget {
  @override
  State<MyDetailsButton> createState() => _MyDetailsButtonState();
}

class _MyDetailsButtonState extends State<MyDetailsButton> {
  bool _isLoading = false;

  void _showDialog() {
    setState(() => _isLoading = false);
    showDialog(
      context: context,
      builder: (_) => const AlertDialog(
        title: Text('Alert'),
      ),
    );
  }
  
  Future<void> _fetchBackEndData() async {
    // Any call to your asynchronous operation
    await Future.delayed(const Duration(seconds: 2));
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: Colors.orange,
      ),
      onPressed: () {
        setState(() => _isLoading = true);
        
        // Call to your backend
        _fetchBackEndData().then((_) => _showDialog());
      },
      child: _isLoading
          ? const CircularProgressIndicator()
          : const Text('Details'),
    );
  }
}

In this code sample I am changing the state of my button so it display a loading indicator and then make an asynchronous call to my method _fetchBackEndData() and by using the then() callback I can display a dialog after my asynchronous method is done.

Try the full code on DartPad

Related