Flutter forms with GetX
In Flutter, forms are a way to collect user input in a structured manner. Flutter provides the Form widget as a container for form elements, and it includes a set of form-related widgets and classes to help manage and validate user input.
If you need simple text input without form validation, TextField may be sufficient.
If you are working with forms and need built-in validation support, TextFormField is a more appropriate choice. In many cases, TextFormField is preferred for forms as it provides a convenient way to handle validation and other form-related features.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(const MainApp());
}
class FormProcessor extends GetxController {
final emailController = TextEditingController();
final passwordController = TextEditingController();
void submitForm() {
String email = emailController.text;
String password = passwordController.text;
print('Email: $email, Password: $password');
}
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: ThemeData(
primarySwatch: Colors.green,
),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
final FormProcessor fp = Get.put(FormProcessor());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Form Example'),
),
body: Padding(
padding: EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: fp.emailController,
maxLength: 10,
decoration: InputDecoration(
labelText: 'Email',
prefixText: '+94 ',
suffixText: ' Sri Lanka ',
helperText: 'Please type your email here',
suffixIcon: Icon(
Icons.visibility,
color: Colors.red,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(color: Colors.grey)))),
SizedBox(height: 20),
TextField(
controller: fp.passwordController,
decoration: InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: BorderSide(color: Colors.grey))),
obscureText: true,
obscuringCharacter: "x",
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
fp.submitForm();
},
child: Text('Submit'),
)
],
),
),
);
}
}
More information:
- https://docs.flutter.dev/ui/design/material
- https://api.flutter.dev/flutter/material/TextFormField-class.html
- https://codesinsider.com/flutter-textfield-widget-tutorial/