Skip to content

Instantly share code, notes, and snippets.

@moritzmorgenroth
Last active August 13, 2021 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save moritzmorgenroth/cbfdebfa526548d56b6a9e7116b1c0c9 to your computer and use it in GitHub Desktop.
Save moritzmorgenroth/cbfdebfa526548d56b6a9e7116b1c0c9 to your computer and use it in GitHub Desktop.
Flutter example for async form validation
class UsernameForm extends StatefulWidget {
final Function onSuccess;
UsernameForm(this.onSuccess);
@override
_UsernameFormState createState() => _UsernameFormState(onSuccess);
}
class _UsernameFormState extends State<UsernameForm> {
final _formKey = GlobalKey<FormState>();
String _username;
bool _usernameTaken = false;
bool _success = false;
final Function onSuccess;
_UsernameFormState(this.onSuccess);
@override
Widget build(BuildContext context) {
// auto validate the form when the state changes
_formKey.currentState?.validate();
return Container(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
validator: (value) {
print("validating...");
if (value.isEmpty) {
return 'Please enter a name';
}
if (_usernameTaken) {
return 'Username is taken';
} else if (!_success) {
_saveUsername();
}
},
onSaved: (value) {
_username = value;
_checkUsername(value);
},
cursorColor: Palette.colorTextPrimary,
decoration: new InputDecoration(
hintText: "Username",
labelText: "Pick a username",
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
onPressed: () {
// Validate will return true if the form is valid, or false if
// the form is invalid.
_formKey.currentState.save();
},
child: Text('Submit'),
),
),
],
),
),
);
}
_saveUsername() {
FirebaseAuth.instance.currentUser().then((value) {
Firestore.instance
.collection('usernames')
.document(_username)
.setData({'a': true}).then((val) {
Firestore.instance
.collection('users')
.document(value.uid)
.setData({'name': _username}).then((val) {
print("success");
setState(() {
_success = true;
});
this.onSuccess();
});
});
});
}
_checkUsername(String username) {
if (username != null && !username.isEmpty) {
Firestore.instance
.collection('usernames')
.document(username)
.get()
.then((value) {
setState(() {
_usernameTaken = value.data != null;
});
});
} else {
setState(() {
_usernameTaken = true;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment