Open In App

Flutter – Assigning Actions to Buttons

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. Flutter provides a number of prebuilt widgets to use. There are different types of Button widgets that are provided by the Flutter SDK. In this article, we are going to see how we can add actions to them.

Below are some button widgets that are shipped with Flutter SDK:

  • TextButton
  • ElevatedButton
  • OutlinedButton
  • IconButton
  • FloatingActionButton

Actions are assigned using onPressed() function. We are going to see two methods to assign Actions.

Note: We are not going to use any other dependencies for this application.

Method 1

This method is currently deprecated. We can use the second method instead to get the same results.

Using function reference. In this method, we are going to define a function somewhere else and then use that function’s reference as an action. This method is recommended because you can reuse the same function more than once.

Dart




import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
 
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: ButtonsExample(),
    );
  }
}
 
// list all the buttons
class ButtonsExample extends StatelessWidget {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
 
  void textButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Text/ Flat Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
 
  void elevatedButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Elevated/ Raised Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
 
  void outlineButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Outline/ Outlined Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
 
  void iconButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Icon Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
 
  void floatingActionButtonHandler() {
    scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Floating Action Button'),
        duration: Duration(seconds: 1),
      ),
    );
  }
   
  // assign actions to
  // all the listed buttons
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: scaffoldKey,
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextButton(
                onPressed: textButtonHandler,
                child: Text('Text Button'),
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                onPressed: textButtonHandler,
                child: Text('Flat Button'),
              ),
              ElevatedButton(
                onPressed: elevatedButtonHandler,
                child: Text('Elevated Button'),
              ),
              RaisedButton(
                onPressed: elevatedButtonHandler,
                child: Text('Raised Button'),
              ),
              OutlineButton(
                onPressed: outlineButtonHandler,
                child: Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: outlineButtonHandler,
                child: Text('Outlined Button'),
              ),
              IconButton(
                icon: Icon(Icons.star),
                onPressed: iconButtonHandler,
              ),
              FloatingActionButton.extended(
                onPressed: floatingActionButtonHandler,
                label: Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:

If you need to pass some arguments to the functions then, use the following approach:

onPressed: () => nameOfFunction(...args)

-- OR --

onPressed: () {
  nameOfFunction(...args);
}

Method 2: 

Define function directly where the Button widget is used, This method is not well suited for big apps because this makes the app less readable and cause problems during debugging and if the same function is used more than once then you have to repeat code which is also not very good practice.

Dart




import 'package:flutter/material.dart';
 
void main() => runApp(const MyApp());
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
 
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: ButtonsExample(),
    );
  }
}
 
// list all the buttons
class ButtonsExample extends StatelessWidget {
  // const ButtonsExample ({Key ?key}) : super(key:key);
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
 
  ButtonsExample({Key? key}) : super(key: key);
 
  // ignore: avoid_print
 
// assign actions to
// all the listed buttons
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: scaffoldKey,
        appBar: AppBar(
          title: const Text('GeeksforGeeks'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Center(
                child: TextButton(
                  onPressed: (() {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text("Text / Flat Button"),
                        duration: Duration(seconds: 1),
                      ),
                    );
                  }),
                  child: const Text('Text Button'),
                ),
              ),
              // FlatButton is Deprecated and will be removed in the future.
              // We recommend using TextButton instead.
              // FlatButton(
              //   minWidth: MediaQuery.of(context).size.width,
              //   onPressed: () {
              //     ScaffoldMessenger.of(context).showSnackBar(
              //       const SnackBar(
              //         content: Text("Text / Flat Button"),
              //         duration: Duration(seconds: 1),
              //       ),
              //     );
              //   },
              //   child: const Text('Flat Button'),
              // ),
              ElevatedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text("Elevated / Raised Button"),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: const Text('Elevated Button'),
              ),
              // RaisedButton is Deprecated and will be removed in the next release.
              // Use ElevatedButton instead.
              // RaisedButton(
              //   onPressed: () {
              //     ScaffoldMessenger.of(context).showSnackBar(
              //       const SnackBar(
              //         content: Text("Elevated / Raised Button"),
              //         duration: Duration(seconds: 1),
              //       ),
              //     );
              //   },
              //   child: const Text('Raised Button'),
              // ),
              OutlinedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text("Outline / Outlined Button"),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: const Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text("Outline  / Outlined Button"),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: const Text('Outlined Button'),
              ),
              IconButton(
                icon: const Icon(Icons.star),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text("Icon Button"),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text("Floating Action Button"),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                label: const Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads