Flutter FloatingActionButton – onPressed

You can execute a set of dart statement when user taps on a FloatingActionButton using onPressed callback.

onPressed callback is called when user taps or otherwise activates the FloatingActionButton.

Note: If onPressed property is not set or set to null, the FloatingActionButton is displayed as disabled.

Following is the quick code snippet to use onPressed property with FloatingActionButton.

FloatingActionButton(
  //other properties
  onPressed: () {
    //your code to execute when user presses/taps on the FAB
  },
),

Example: FloatingActionButton onPressed()

In this example Flutter Application, we shall create a FlutterActionButton and set the onPressed property with a function. In the function, you can write your application specific functionality. For this example, we shall just print a message to the console.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("Flutter Tutorial - googleflutter.com"),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: () {
          //your dart code
          print('Yeah.. The FloatingActionButton is pressed.');
        },
      ),
    );
  }
}

Output

When you run the above Flutter Application, a screen is displayed with FloatingActionButton at the bottom right corner. Tap on it, and you shall see a statement printed to the console.

Summary

In this Flutter Tutorial, we learned how to use onPressed property of FloatingActionButton, to execute a set of dart statements when user presses or taps on the floating action button.

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.