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;
}
}
Refer here to show the dialog.
Send context
to _loginButtonClickHandler
and you are done. Cheers
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;
},
);
}
BuildContext
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With