I like to check if an email already exists in the database on my backend. Therefore I tried to use a state var which should be changed after the async call returns. I found the following threads which contains accepted answeres.
Flutter - Async Validator of TextFormField
Flutter firebase validation of form field inputs
I tried these answeres and also some variations but it still doesn't work for me. I just simulate the backend call. Setting _emailExist to true is printed but I don't see any error. If I click the button twice, the error message is shown correctly.
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
LoginPage({Key key}) : super(key: key);
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();
bool _emailExist = false;
@override
initState() {
super.initState();
}
checkEmail(String name) {
// Simulare async call
Future.delayed(Duration(seconds: 2)).then((val) {
setState(() {
_emailExist = true;
});
print(_emailExist);
});
return _emailExist;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Test"),
),
body: Container(
child: SingleChildScrollView(
child: Form(
key: _loginFormKey,
child: Column(
children: <Widget>[
TextFormField(
validator: (value) =>
checkEmail(value) ? "Email already taken" : null,
),
RaisedButton(
child: Text("Login"),
onPressed: () {
if (_loginFormKey.currentState.validate()) {}
},
)
],
),
))));
}
}