Flutter - Assigning Actions to Buttons - GeeksforGeeks

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.
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 buttonsclass 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);
}
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 buttonsclass 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:
Picked
Technical Scripter 2020
Dart
Flutter
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Android Studio Setup for Flutter Development
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Dialogs