Welcome back to your Flutter journey! So far, we've learned how to build static UIs. But a truly engaging app needs to respond to user input. This is where buttons and event handling come in. In Flutter, widgets like ElevatedButton, TextButton, and OutlinedButton are your go-to for creating interactive elements that users can tap.
At its core, event handling in Flutter is about listening for specific actions (like a button tap) and then executing a defined piece of code in response. This response is often referred to as a 'callback' – a function that gets called back when an event occurs.
Let's start with a basic ElevatedButton. The most crucial property for making it interactive is onPressed. This property accepts a function that will be executed whenever the button is tapped. If you don't provide a function, the button will be disabled (appearing grayed out).
ElevatedButton(
onPressed: () {
// Code to execute when the button is pressed
print('Button Tapped!');
},
child: Text('Tap Me'),
)In this simple example, when the ElevatedButton is tapped, the print('Button Tapped!'); statement will execute, and you'll see 'Button Tapped!' in your debug console. The child property, as we've seen before, defines what appears inside the button.
You can use the onPressed callback to do much more than just print to the console. You can update the app's state, navigate to different screens, perform calculations, or trigger network requests. This is the foundation of making your app dynamic.
Consider a scenario where you want to change some text on the screen when a button is pressed. This involves managing the app's state. For simple state changes within a single widget, setState is your best friend. It tells Flutter that the internal state of the widget has changed and that the UI needs to be rebuilt to reflect those changes.
import 'package:flutter/material.dart';
class InteractiveCounter extends StatefulWidget {
@override
_InteractiveCounterState createState() => _InteractiveCounterState();
}
class _InteractiveCounterState extends State<InteractiveCounter> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}