Handling User Interactions in Flutter
Handling User Interactions in Flutter
Interactions in
Flutter
What is User Interaction?
User interaction refers to how users engage with an app using
touch, gestures, and input.
Examples include:
• Pressing buttons
• Swiping
• Typing in text fields
• Dragging & long pressing
Handling Button Clicks
Buttons are the most common interactive elements
Example
ElevatedButton(
onPressed: () {
print('Button Clicked!');
},
child: Text('Click Me'),)
Detecting Gestures with GestureDetector
GestureDetector allows us to detect taps, swipes, long presses, etc.
Example:
GestureDetector(
onTap: () {
print('Container tapped!');
},
child: Container(
color: Colors.blue,
width: 100,
height: 100,
),
)
Handling Long Press & Double Tap
GestureDetector can detect different gestures
Example:
GestureDetector(
onLongPress: () {
print('Long Press Detected');
},
child: Icon(
Icons.favorite,
size: 50,
color: Colors.red
),
)
Dragging & Swiping in Flutter
Swiping & dragging gestures are useful for lists & animations
Example: Detecting horizontal swipe
GestureDetector(
onHorizontalDragEnd: (details) {
print('Swiped Horizontally!');
}, child: Container(
width: 200,
height: 100,
color: Colors.green,
),
)
Handling Text Input
TextField allows users to enter text
Example:
TextField(
decoration: InputDecoration(
labelText: 'Enter your name'),
onChanged: (text) {
print('User typed: $text');
},
)
Handling Forms & Validation
Use TextFormField with Form widget
Example of validating input:
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
)
Assignment
1. What is user interaction in mobile applications, and why is it
important?
2. Explain how button clicks are handled in Flutter. Provide a simple
code example.
3. What is the purpose of GestureDetector in Flutter? List at least three
gestures it can detect.
4. How does TextField work in Flutter? Provide an example of a
TextField that captures user input.
5. What is form validation, and why is it important in apps?