Flutter Button onPressed() Tutorial

Flutter Button on Pressed

In this tutorial, we will learn how to execute a function when user pressed a button.

To execute a function when button is pressed, use onPressed() property of the button.

Sample Code Snippet

Following is a sample code snippet to execute a function when RaisedButton is pressed.

RaisedButton(
  onPressed: () => {
	//do something
  },
  child: new Text('Click me'),
),

Example

In this example Flutter Application, we shall take a RaisedButton and execute a function when the button is pressed.

To recreate this Button onPressed() example, create an empty Flutter Application and replace main.dart with the following code.

main.dart

import 'package:flutter/material.dart';

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

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

class _State extends State<MyApp> {
  int count = 0;

  void incrementCounter() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Flutter Tutorial - googleflutter.com'),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: () => {
            incrementCounter()
          },
          child: new Text('Button Clicks - ${count}'),
        ),
      ),
    );
  }
}

This this flutter application, and you should see an UI similar to that of the following. When you press the button, we shall execute a function to increment the counter placed in the button text.

Summary

In this Flutter Tutorial, we learned how to respond to a Button press action and execute a function using onPressed property.

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.