Event Handling
Learning Objectives
- You know of the concept of events in Flutter and know in general how events are processed.
- You know of widgets in Flutter that can be interacted with and how to give them functions that are executed when interacted with.
Flutter has a range of widgets that can be interacted with, such as buttons, sliders, and text fields. These widgets can be given functions that are executed when the user interacts with them. Events, broadly, are actions triggered by the user or the application that need to be processed. With interactive user interfaces, the processing of events is often asynchronous — whenever an event happens, the function or functions related to the event is added to a queue, which is is processed at some point in the future.
If event processing would be synchronous, the application would freeze whenever an event happens, which could make the application unresponsive and slow.
Widgets in Flutter have event-specific properties that can be given functions that are to be called whenever an event happens. For example, Flutter has a range of buttons that have a property onPressed that is given a function that is executed when the button is pressed.
The following example demonstrates an OutlinedButton with the text “Hello world!”.
When the button is pressed, the function given to onPressed
is executed. In the above example, the function is empty, meaning that nothing happens. Regardless, when you try pressing the button, you can see a brief animation indicating that the button was pressed — this stems from Flutter’s default behavior for buttons.
The function that is given as an argument to
onPressed
is an example of a callback function. A callback function is passed as an argument to another function or as a property to a widget, and it is executed at some point in the future, for example, when an event happens. Above, the function is also anonymous, meaning that it does not have a name.
The function given to the onPressed
property can be any function. For example, the following application shows how a small message for a short period of time is shown when the button is pressed. For the message, a SnackBar widget is created, and it is shown with the help of a ScaffoldMessenger.
With event handling, it is possible to add navigation to the application and to, for example, create widgets that change their appearance when interacted with. In the next part, we look into how to navigate between screens in Flutter applications.