This is as simple as it gets (well almost!). A simple login form in Flutter, the UI only.
We have initial focus, we have two controllers for our fields, and one of them is password so that you can’t see the actual input and then we have a button. Ready to be used!
import 'package:flutter/material.dart';
// Define a custom Form widget.
class LoginForm extends StatefulWidget {
const LoginForm({Key? key}) : super(key: key);
@override
_LoginFormState createState() => _LoginFormState();
}
// Define a corresponding State class.
// This class holds data related to the form.
class _LoginFormState extends State<LoginForm> {
// Define the focus node. To manage the lifecycle, create the FocusNode in
// the initState method, and clean it up in the dispose method.
late FocusNode myFocusNode;
final usernameController = TextEditingController();
final passwordController = TextEditingController();
@override
void initState() {
super.initState();
myFocusNode = FocusNode();
usernameController.addListener(() {
print("current value! " + usernameController.text);
});
passwordController.addListener(() {
print("current value! " + passwordController.text);
});
}
@override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
usernameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final ButtonStyle style =
ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// The first text field is focused on as soon as the app starts.
TextField(
autofocus: true,
controller: usernameController,
decoration: new InputDecoration(hintText: "Email"),
),
// The second text field is focused on when a user taps the
// FloatingActionButton.
TextField(
focusNode: myFocusNode,
decoration: new InputDecoration(hintText: "Password"),
controller: passwordController,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
),
ElevatedButton(
style: style,
onPressed: () {},
child: const Text('Login'),
),
],
),
);
}
}
Then we can use it like this anywhere in a Widget:
Container(
child: LoginForm()
),