Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Last active Mar 19, 2020
Embed
What would you like to do?
"Build Your Own Forms in Flutter" video tutorial
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: PageForm()
)
)
));
class PageForm extends StatefulWidget {
@override
_PageFormState createState() => _PageFormState();
}
class _PageFormState extends State<PageForm> {
final _formKey = GlobalKey<FormState>();
var _autovalidate = false;
var _user;
var _password;
var _passwordRepeat;
@override
Widget build(BuildContext context) {
return Form(
autovalidate: _autovalidate,
key: _formKey,
child: Column(
children: <Widget>[
FlutterLogo(size: 100),
SizedBox(height: 20),
Text('Sign up',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30,
color: Colors.grey,
)),
SizedBox(height: 30),
TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Username'
),
onChanged: (value) {
_user = value;
},
validator: (value) {
if (value.isEmpty) {
return 'Please enter your username';
}
return null;
}
),
SizedBox(height: 20),
TextFormField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password'
),
onChanged: (value) {
_password = value;
},
validator: (value) {
if (value.isEmpty) {
return 'Please enter your password';
}
return null;
}
),
SizedBox(height: 20),
TextFormField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Repeat password'
),
onChanged: (value) {
_passwordRepeat = value;
},
validator: (value) {
if (_password != value) {
return 'Passwords do not match';
}
return null;
}
),
SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: FlatButton(
color: Colors.blue,
child: Text('Submit', style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
)),
onPressed: () {
if (_formKey.currentState.validate()) {
print('$_user:$_password:$_passwordRepeat');
Scaffold.of(context)
.showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text('Submitted successfully :)')
));
} else {
Scaffold.of(context)
.showSnackBar(SnackBar(
backgroundColor: Colors.redAccent,
content: Text('Problem submitting form :(')
));
setState(() {
_autovalidate = true;
});
}
}
)
)
]
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment