Flutter RaisedButton – onPressed
The onPressed property defines the callback that runs when a Flutter button is pressed. In older Flutter code, this was commonly used with RaisedButton. RaisedButton has since been deprecated and removed from current Flutter releases; its direct replacement is ElevatedButton. The callback pattern itself remains the same.
If you are maintaining older Flutter code that still uses RaisedButton, the examples below explain how its onPressed callback works. For new Flutter applications, use the ElevatedButton examples in the later sections.
RaisedButton onPressed Callback Syntax
Flutter RaisedButton’s onPressed property lets you assign it with a callback function. The application executes this callback function when user presses on the RaisedButton.
In this tutorial, we will learn how to execute a set of statements using callback function for onPressed property of RaisedButton.
Following is a code snippet of how you write the callback for onPressed property.
RaisedButton(
child: Text(
'Login',
),
onPressed: () {
//statement(s)
},
),
The anonymous function assigned to onPressed is called when the button is activated. Statements inside the callback can call another function, update state, validate input, start an asynchronous operation, or navigate to another route.
Example – Perform Action when User presses Flutter RaisedButton
In this example, we have a RaisedButton that displays a button with Login text. So, it appears like a Login button. Also, we have initialized onPressed property of this button with a callback function.
When user presses this button, this callback function is called. The application executes all the statements inside this callback function. In this example application, we have written a print statement, for demonstrating the working of onPressed property. You may replace that with as many statements that emulate a required functionality as per the requirement of your application.
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter RaisedButton - tutorialkart.com'),
),
body: Center(
child: Container(
child: RaisedButton(
child: Text(
'Login',
style: TextStyle(fontSize: 20),
),
color: Colors.green,
textColor: Colors.white,
onPressed: () {
print('You pressed the button.');
},
),
),
),
),
);
}
}
Run this application. You can run it on an Android Emulator, or a Real Android Device. The result shall be more or less the same as shown in the following screenshot.
)
When user presses on the button, the callback executes the statements and prints a string to the console as shown in the console window below.
)
Use ElevatedButton onPressed in Current Flutter Code
Flutter replaced RaisedButton with ElevatedButton. For a new application, the equivalent button uses the same onPressed callback structure:
ElevatedButton(
onPressed: () {
print('You pressed the button.');
},
child: const Text('Login'),
)
The main migration is the widget name and styling API. Older properties such as color and textColor are replaced by the button’s style, commonly created with ElevatedButton.styleFrom().
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
onPressed: () {
print('You pressed the button.');
},
child: const Text('Login'),
)
The Flutter migration guide documents ElevatedButton as the replacement for RaisedButton: Flutter button migration guide.
Call a Dart Function from Flutter onPressed
If the action already exists as a function, pass the function reference to onPressed. Do not add parentheses when you want Flutter to call the function later in response to the button press.
void login() {
print('Login function called.');
}
ElevatedButton(
onPressed: login,
child: const Text('Login'),
)
Writing onPressed: login passes the callback. Writing login() calls the function immediately while the widget is being built, so it is not the form to use for a normal button callback.
Pass Arguments from onPressed to a Flutter Function
When the function needs arguments, wrap the function call in an anonymous callback. Flutter invokes the callback when the button is pressed, and the callback then calls your function with the required values.
void login(String username) {
print('Logging in $username');
}
ElevatedButton(
onPressed: () {
login('Alex');
},
child: const Text('Login'),
)
Update StatefulWidget UI from a Button onPressed
Calling a callback does not by itself tell a StatefulWidget to rebuild. When a button changes state that is displayed by the widget, make the change inside setState().
int count = 0;
ElevatedButton(
onPressed: () {
setState(() {
count++;
});
},
child: const Text('Increase'),
)
After the callback changes count, setState() schedules a rebuild so widgets that depend on that value can display the new state.
Navigate to Another Flutter Page from onPressed
A button can open another page by calling Navigator.push() from its onPressed callback. The callback has access to the current BuildContext when it is created inside the widget’s build() method.
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DetailsPage(),
),
);
},
child: const Text('Open Details'),
)
This pushes DetailsPage onto the navigator stack. The destination widget must be defined in the application.
Disable an ElevatedButton by Setting onPressed to null
For current Material buttons such as ElevatedButton, setting onPressed to null disables the button when no other activation callback enables it. This is useful when an action should only be available after a condition is met.
ElevatedButton(
onPressed: isFormValid ? submitForm : null,
child: const Text('Submit'),
)
When isFormValid is true, submitForm is assigned as the callback. When it is false, onPressed becomes null and the button is disabled.
Run an Async Function from Flutter onPressed
An onPressed callback can be marked async when the button starts asynchronous work such as saving data or waiting for a service call.
ElevatedButton(
onPressed: () async {
await saveData();
print('Data saved.');
},
child: const Text('Save'),
)
For longer operations, applications commonly track a loading state so repeated presses can be prevented while the operation is in progress.
RaisedButton onPressed Migration to ElevatedButton
The older RaisedButton examples on this page show the original API and are useful when reading or maintaining legacy Flutter projects. In current Flutter code, use ElevatedButton for the equivalent raised Material button. The central idea remains unchanged: provide a non-null callback to onPressed for an enabled action, place the required statements in that callback or call another function from it, and use null when the action should be disabled.
In this Flutter Tutorial, we learned how to perform an action or execute a set of statements when user presses on a button in your Flutter application.
TutorialKart.com