Overview of the onPressed Method
Explore the fundamental concept of the onPressed method within Flutter's ElevatedButton widget. Understand how to use callback functions to handle user interactions, toggle button states, and manage widget behavior. This lesson helps you grasp how functions and callbacks work in Dart to implement responsive UI elements.
What is the onPressed method
The Flutter framework helps us to build beautiful design patterns. If you have already learned Flutter a little bit, then you may have learned that you cannot drag and drop interfaces. Instead, you need to write the necessary code.
However, since the coding part involves only the Dart programming language, it becomes easier for us. Given that we must have a basic Dart programming concept for this section of the course.
Any User Interface needs interaction from the user. The Flutter app should allow users to interact with itself, no matter how we design that app.
As long as we think of UI and interaction, we can think of the behaviour of a simple button. If we press that button, it should call a method in our widget class.
For example, think about the ElevatedButton widget that uses a callback through the onPressed method.
In this article, we will understand this fundamental concept of onPressed in Flutter.
How to use the onPressed method?
To understand the onPressed method, we need to use it inside a Flutter app first.
The following image represents a button app, which we will build step by step:
First, we will import material and call our main OurApp class using the void main runApp() method.
The next step involves creating an OurApp class that extends a StatelessWidget. The OurApp class should have a build() method.
import 'package:flutter/material.dart';
void main() {
runApp(OurApp());
}
class OurApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Our App',
debugShowCheckedModeBanner: false,
home: Scaffold(
body: ACenterClass(),
),
);
}
}
class ACenterClass extends StatefulWidget {
@override
_ACenterClassState createState() => _ACenterClassState();
}
class _ACenterClassState extends State<ACenterClass> {
String txtMessage = "Button Off";
void pressRemote() {
setState(() {
if (txtMessage == "Button Off") {
txtMessage = "Button On";
} else {
txtMessage = "Button Off";
}
});
}
@override
Widget build(BuildContext context) {
return Center(
child: new SingleChildScrollView(
child: Container(
alignment: Alignment.center,
width: 350.00,
height: 200.00,
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(
color: Colors.deepOrange,
width: 2.0,
style: BorderStyle.solid,
),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 20.0,
spreadRadius: 20.0,
),
],
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.red,
Colors.white,
],
),
// to make shape active we need to comment out borderRadius property and vice versa
//shape: BoxShape.circle,
),
child: Column(
children: [
Text(
'Press:',
style: TextStyle(
fontSize: 30.0,
color: Colors.black,
),
),
SizedBox(
height: 10.0,
),
ElevatedButton(
child: Text(
'Press Button',
style: TextStyle(
fontSize: 30.0,
color: Colors.white,
),
),
onPressed: pressRemote,
),
SizedBox(
height: 30.0,
),
Text(
txtMessage,
style: TextStyle(
fontSize: 38.0,
color: Colors.black,
),
),
],
),
),
),
);
}
}
As we can see in the above code, we have called a function pressRemote(), or we can call it a method since it is inside a class.
Calling functions in Flutter
How did we call a function in Flutter? We have created a standalone class named ACenterClass that extends a StatefulWidget.
Inside ACenterClass, we have created a function pressRemote() that changes the displayed message when the user presses the ElevatedButton.
When we press the button, it changes the Text widget’s state that displays the button message. It will change its message from “Button Off” to “Button On” and vice versa.
However, there is a problem.
Inside the ElevatedButton widget onPressed callback we have passed a reference to the pressRemote() function. See the code below:
We cannot write like this.
To understand the onPressed method and why we cannot write like this, we need to first understand functions in Dart programming.
What is a function?
A function is a block of code that acts as an algorithm separated logically from other code so we can reuse it. We can also refer to it as the method in the context of an object.
A function can return nothing (void) or return a built-in or custom data type.
It can also take zero or more parameters to reference in its algorithm.
The ElevatedButton widget, through its constructor, uses onPressed as a callback function.
A second look at callbacks
As a reminder, a Callback is a function or a method that we pass as an argument into another function or method.
Exactly this happens here. We have passed onPressed as a named argument into the ElevatedButton constructor.
And what happens after that?
The onPressed method performs a specific task and uses the callback concept.
Let us see an almost similar code executable in Dart. Just press the “Run” button to execute the Dart code:
In the above code, we have just referenced the function, and it returns a value.