πBasic Interactivity
Creating interactive user interfaces is at the heart of app development. Flutter provides various widgets and mechanisms to handle user interactions. Let's explore how to make your app interactive!
1. Handling Button Presses π±οΈ
Buttons are the simplest interactive widgets. Here's how you can create a button and handle its press event:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
void handlePress() {
print('Button Pressed!');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Button Example'),
),
body: Center(
child: ElevatedButton(
onPressed: handlePress,
child: Text('Press me'),
),
),
),
);
}
}
2. Handling Text Input π
Text fields allow users to input text. Hereβs how you can create a text field and retrieve its value:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final TextEditingController textController = TextEditingController();
void handleSubmit() {
print('User Input: ${textController.text}');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Text Input Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: textController,
decoration: InputDecoration(labelText: 'Enter something'),
),
ElevatedButton(
onPressed: handleSubmit,
child: Text('Submit'),
)
],
),
),
),
);
}
}
3. Using Gesture Detectors π
Gesture detectors can identify various gestures, like taps, double-taps, drags, and pinches. Hereβs a simple tap handler: (Try it yourself in your IDE!)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
void handleTap() {
print('Box tapped!');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Gesture Detector Example'),
),
body: Center(
child: GestureDetector(
onTap: handleTap,
child: Container(
color: Colors.blue,
width: 200,
height: 200,
child: Center(
child: Text(
'Tap me',
style: TextStyle(color: Colors.white),
),
),
),
),
),
),
);
}
}
Assignments π
Letβs reinforce your learning with some hands-on tasks:
Ready for the next challenge? Dive into Navigation to learn how to move between different screens in your app!
Last updated
Was this helpful?