1

Forgive me if its a noob question or the code seems too basic, I am new to flutter. I have done my fair share of googling but i havent been able to find a solution.

As soon as the future function starts, i want to show the Loading alert. When the API request/response is processed, if an error has occurred it should be shown in showErrorDialog, and the LoadingDialog should be dismissed automatically.

Right now, ErrorDialog shows and can be dismissed with its button, but then LoadingDialog does not get dismissed.

I can do it with Future.delayed but that is simply a work around has has too many variable outcomes. Here is dummy code:

import 'package:flutter/material.dart';

class RandomScreen extends StatefulWidget {
  @override
  _RandomScreenState createState() => _RandomScreenState();
}

class _RandomScreenState extends State<RandomScreen> {

  Future<void> _submitApiRequest() async {
    try {
      _showLoadingAlert();

      //processing the API request/response here.

    } catch (error) {
      _showErrorDialogue(error.toString());
    }
  }

  void _showErrorDialogue(String errorMessage) {
    showDialog(
      context: context,
      builder: (ctx) => Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.0),
        ),
        child: Column(
          children: <Widget>[
            Text(errorMessage),
            FlatButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(
                'Dismiss',
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showLoadingAlert() {
    showDialog(
      context: context,
      builder: (ctx) => CircularProgressIndicator(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Random Screen'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: _submitApiRequest,
          child: Text('Submit'),
        ),
      ),
    );
  }
}
Hassan Hammad
  • 172
  • 1
  • 9

1 Answers1

0

The Way you are trying to do might not be the best way in case you are trying to call API and show a loading screen . I would recommend you to use ModalProgressHud

This will show a loader while you are trying to do API call and once API response received you can hide the loader using a state variable.

In case you still want to do using alert box , you need to call Navigator.pop as mentioned in documentation.

If the application has multiple Navigator objects, it may be necessary to call Navigator.of(context, rootNavigator: true).pop(result) to close the dialog rather than just Navigator.pop(context, result).

Sanjay
  • 117
  • 4
  • 13
  • I have already seen this answer somewhere, and it seems like a little too complex an approach. The comment on my question by @Suman Maharjan gave me the optimum solution for my case. Thanks for taking the time to reply though :) – Hassan Hammad Mar 23 '20 at 09:56