Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter : Show an Alert Dialog after an async Api call

This is the code to get the Login response. If there is an error I want to show an Alert dialog saying that there was an error during Login.

Future<String> login(String username, String password) async {
    Map<String, dynamic> params = {
       'username': username,
       'password': password,
    };

    final response = await http.post('apiurl', body: params);

    if (response.statusCode != 200)
       throw Exception(response.body);

    return response.body;
}

I'm adding the code from where the call to login happens. There is a TODO in the _loginController where I want to Show an Alert Dialog which shows the error.

class LoginWidgetState extends State<LoginWidget> {
  var _usernameController = new TextEditingController();

  var _passwordController = new TextEditingController();

  void _loginButtonClickHandler() {
    var username = _usernameController.text;
    var password = _passwordController.text;

    login(username, password).then((response) {

    }).catchError((e) {
      //TODO : show an Alert Here
    });
  }

  @override
  Widget build(BuildContext context) {
    var container = Center(
      child: Container(
    child: Column(
      children: <Widget>[
        TextField(
          decoration: InputDecoration(
            hintText: "username",
          ),
          controller: _usernameController,
        ),
        TextField(
          obscureText: true,
          decoration: InputDecoration(hintText: "password"),
          controller: _passwordController,
        ),
        RawMaterialButton(
          onPressed: _loginButtonClickHandler,
          child: Text("Login"),
        )
       ],
     ),
    ),
   );

   return container;
  }

}
like image 575
Anup Ammanavar Avatar asked Aug 14 '18 12:08

Anup Ammanavar


2 Answers

Refer here to show the dialog.

Send context to _loginButtonClickHandler and you are done. Cheers

like image 160
Dinesh Balasubramanian Avatar answered Nov 18 '22 07:11

Dinesh Balasubramanian


To give more context to the accepted answer...

If you make a remote API call like this:

login(username, password).then((response) {

}).catchError((e) {
  //TODO : show an Alert Here
});

then you can replace the TODO with this (if you are calling it from a button click):

_showAlertDialog(context);

Or this (if you are calling it from within a build() method or initState():

WidgetsBinding.instance.addPostFrameCallback((_) => _showAlertDialog(context));

Where the method is defined as

void _showNewVersionAvailableDialog(BuildContext context) {
  final alert = AlertDialog(
    title: Text("Error"),
    content: Text("There was an error during login."),
    actions: [FlatButton(child: Text("OK"), onPressed: () {})],
  );

  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
}

Notes

  • You need to have a reference to the BuildContext.
  • For more info about addPostFrameCallback, read this article.
like image 2
Suragch Avatar answered Nov 18 '22 07:11

Suragch