Day 9: Handling User Input in Flutter
Harpal Matholiya
Mobile Application Developer | 3+ Years Experience | Worked on 50+ Projects | 4.7/5 Rating | Building Scalable, User-Centric Apps | Quality-Driven | Innovation-Focused | Committed to Excellence
Topic: Capturing User Input with TextField and Forms Details: Discuss how to handle user input in Flutter using the TextField widget and Form widget. Explain how to validate user input and manage form state.
Post:
Title: Handling User Input in Flutter
Handling user input is a crucial part of app development. In Flutter, the TextField and Form widgets are used to capture and validate user input. Here’s how you can use them effectively:
领英推荐
Here’s an example to demonstrate how to capture user input and validate it using these widgets:
User Input Example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('User Input Example'),
),
body: MyCustomForm(),
),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
@override
_MyCustomFormState createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Enter your name'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Enter your email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Processing Data')),
);
}
},
child: Text('Submit'),
),
),
],
),
),
);
}
}
By using TextField and Form widgets, you can efficiently capture and validate user input in your Flutter apps.
Ready to master Flutter? Join our 30-day development course for just ?5000/month. Learn from experts and build real-world apps. Enroll now! #Flutter #LearnToCode #MobileDevelopment