Skip to content
Related Articles

Related Articles

Improve Article

Flutter – Assigning Actions to Buttons

  • Last Updated : 04 Jan, 2021

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

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(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 &
  // assign actions to 
  // all the listed buttons
class ButtonsExample extends StatelessWidget {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  
  @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: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Text Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Text Button'),
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Flat Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Flat Button'),
              ),
              ElevatedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Elevated Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Elevated Button'),
              ),
              RaisedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Raised Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Raised Button'),
              ),
              OutlineButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outline Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outline Button'),
              ),
              OutlinedButton(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Outlined Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                child: Text('Outlined Button'),
              ),
              IconButton(
                icon: Icon(Icons.star),
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Icon Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  scaffoldKey.currentState.showSnackBar(
                    SnackBar(
                      content: Text('Floating Action Button'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
                label: Text('Floating Action Button'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :