Flutter - Using TextButton Widget Examples

This tutorial contains examples of how to use TextButton widget in Flutter. This includes the basic usage and how to customize the button.

Text Button is a Material Design's button that comes without border or elevation change by default. Therefore, it relies on the position relative to other widgets. It can also be used inside a Card widget or dialog and should be grouped in one of the bottom corners. In Flutter, this button can be created using TextButton widget which was introduced in Flutter 1.22.

Using TextButton

You can create a TextButton in Flutter by calling its constructor.

  const TextButton({
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ValueChanged<bool>? onHover,
    ValueChanged<bool>? onFocusChange,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool autofocus = false,
    Clip clipBehavior = Clip.none,
    MaterialStatesController? statesController
    required Widget? child,
  })

There are two required parameters. You have to pass a Widget as child, typically a Text widget. The other required parameter is onPressed, a callback which is called when the button is pressed.

Basic Usage

The most basic usage only requires you to pass the required parameters

  TextButton(
    child: Text('Woolha.com'),
    onPressed: () {
      print('Pressed');
    }
  )

Output:

Flutter - TextButton - ThemeData Style

Handling Long Press

To delect when the user does long press on the button, you can pass another callback function as onLongPress.

  TextButton(
    child: Text('Woolha.com'),
    onPressed: () {
      print('Pressed');
    },
    onLongPress: () {
      print('Long press');
    },
  )

For detecting other gesture types, you can use Flutter's GestureDetector.

 

Setting Button Style

If you want to change the style of the button, what you have to do is creating a ButtonStyle. The ButtonStyle can be passed as ThemeData's textButtonTheme or TextButton's style.

To pass the ButtonStyle as theme data, you have to create a TextButtonThemeData with the ButtonStyle passed as style parameter in the constructor. Then, pass the TextButtonThemeData as textButtonTheme in the constructor of ThemeData. Setting the style as theme data affects the style of all TextButton widgets under the tree. Creating a ButtonStyle for a TextButton can be done using TextButton.styleFrom.

  import 'package:flutter/material.dart';
  
  void main() => runApp(MyApp());
  
  class MyApp extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: _TextButtonExample(),
        theme: ThemeData(
          textButtonTheme: TextButtonThemeData(
            style: TextButton.styleFrom(
              primary: Colors.purple,
            ),
          ),
        ),
      );
    }
  }
  
  class _TextButtonExample extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Woolha.com Flutter Tutorial'),
        ),
        body: Center(
          child: TextButton(
            child: Text('Woolha.com'),
            onPressed: () {
              print('Pressed');
            },
          ),
        ),
      );
    }
  }

Output:

Flutter - TextButton - ThemeData Style

 

For defining a style for a specific button, you can pass ButtonStyle as style parameter in the constructor of TextButton.

  TextButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.teal,
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Style

 

You can pass ButtonStyle as both ThemeData's textButtonTheme and TextButton's style parameters. Flutter will choose the most specific one which is the one defined as TextButton's style.

What customizations can be created using ButtonStyle? Below are some of the examples.

Setting Colors

Values passed as the parameters of TextButton.styleFrom are converted to construct the properties of ButtonStyle. If you pass a Color as primary, it will be used to construct ButtonStyle's foregroundColor and overlayColor. foregroundColor is used for Text and Icon widgets inside the button, while overlayColor is used to indicate that the button is focused, hovered, or pressed. The Color passed as backgroundColor and shadowColor will be used as ButtonStyle's backgroundColor and shadowColor respectively. You can also pass a Color as onSurface which will be used as ButtonStyle's foregroundColor when the button is disabled, with the opacity set to 0.38.

  TextButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.white,
      backgroundColor: Colors.teal,
      onSurface: Colors.grey,
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Colors

 

Setting Text Style

You can define a TextStyle specific for the button and pass it as textStyle. Passing color in the constructor of TextStyle may not affect the text color. As the solution, you can set the color of the text by passing primary as the parameter of TextButton.styleFrom, as shown in the previous example.

  TextButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.teal,
      onPrimary: Colors.white,
      textStyle: TextStyle(
          color: Colors.black,
          fontSize: 40,
          fontStyle: FontStyle.italic
      ),
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Text Style

 

Setting Shadow and Elevation

To set the elevation of the button, you can pass elevation parameter. When the elevation is not 0, you can set the color of the shadow by passing shadowColor parameter.

  TexButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.teal,
      onPrimary: Colors.white,
      shadowColor: Colors.red,
      elevation: 5,
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Shadow and Elevation

 

Setting Border

It's possible to pass a BorderSide as side parameter which is used to set the border of the button. However, it's recommended to use OutlinedButton if you want to have a button with border.

  TextButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.teal,
      onPrimary: Colors.white,
      side: BorderSide(color: Colors.red, width: 5),
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Border

 

Setting Shape

To change the shape of the button, pass OutlinedBorder as shape parameter. For example, you can pass a BeveledRectangleBorder.

  TextButton(
    child: Text('Woolha.com'),
    style: TextButton.styleFrom(
      primary: Colors.teal,
      onPrimary: Colors.white,
      shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5))),
    ),
    onPressed: () {
      print('Pressed');
    },
  )

Output:

Flutter - TextButton - Shape

Below is the list of named parameters you can pass to TextButton.styleFrom static method.

  • Color? foregroundColor: Foreground color when enabled.
  • Color? backgroundColor: Background color when enabled.
  • Color? disabledForegroundColor: Foreground color when disabled.
  • Color? disabledBackgroundColor: Background color when disabled.
  • Color? shadowColor: The shadow color of the button.
  • Color? surfaceTintColor: The color of the surface tint.
  • Color? iconColor: The color of the icon when enabled.
  • Color? surfaceTintColor: The color of the icon when disabled.
  • double? elevation: The elevation of the button.
  • TextStyle? textStyle: The style for Text widget.
  • EdgeInsetsGeometry? padding: The padding between the button's boundary and its child.
  • Size? minimumSize: The minimum size of the button.
  • Size? fixedSize: The size of the button.
  • Size? maximumSize: The maximum size of the button.
  • BorderSide? side: The outline of the button.
  • OutlinedBorder? shape: The shape of the button.
  • MouseCursor? enabledMouseCursor: The mouse cursor when enabled.
  • MouseCursor? disabledMouseCursor: The mouse cursor when disabled.
  • VisualDensity? visualDensity: How compact is the button's layout.
  • MaterialTapTargetSize? tapTargetSize: yyy.
  • Duration? animationDuration: The minimum size of the area within which the button can be pressed.
  • bool? enableFeedback: Whether to enable acoustic and/or haptic feedback.
  • AlignmentGeometry? alignment: The alignment of the child.
  • InteractiveInkFeatureFactory? splashFactory: InkWell splash factory for showing ink splashes when tapped.

Using TextButton.icon

There is also a factory constructor TextButton.icon that requires you to pass a widget as label and another widget as icon. The factory also requires onPressed callback.

  factory TextButton.icon({
    Key? key,
    required VoidCallback? onPressed,
    VoidCallback? onLongPress,
    ValueChanged<bool>? onHover,
    ValueChanged<bool>? onFocusChange,
    ButtonStyle? style,
    FocusNode? focusNode,
    bool? autofocus,
    Clip? clipBehavior,
    MaterialStatesController? statesController,
    required Widget icon,
    required Widget label,
  })

Below is a basic example of using TextButton.icon.

  TextButton.icon(
    label: Text('Woolha.com'),
    icon: Icon(Icons.web),
    onPressed: () {
      print('Pressed');
    }
  )

Output:

Flutter - TextButton.icon

TextButton Parameters

  • Key? key: The widget's key, used to control if it should be replaced.
  • VoidCallback? onPressed: The callback to be called when the button is tapped.
  • VoidCallback? onLongPress: The callback to be called when the button is long pressed.
  • ValueChanged<bool>? onHover: The callback to be called when a pointer enters or exists the button area.
  • ValueChanged<bool>? onFocusChange: The callback to be called when the focus changes.
  • ButtonStyle? style: Defines the style for the button.
  • FocusNode? focusNode: Focus node of the widget.
  • bool autofocus: Whether this widget will be selected as initial focus. Defaults to false
  • Clip clipBehavior: Defines how the content is clipped. Defaults to Clip.none.
  • MaterialStatesController? statesController: Represents the MaterialState of the widget.
  • Widget? child: The button content.

TextButton.icon Parameters

  • Key? key: The widget's key, used to control if it should be replaced.
  • VoidCallback? onPressed: The callback to be called when the button is tapped.
  • VoidCallback? onLongPress: The callback to be called when the button is long pressed.
  • ValueChanged<bool>? onHover: The callback to be called when a pointer enters or exists the button area.
  • ValueChanged<bool>? onFocusChange: The callback to be called when the focus changes.
  • ButtonStyle? style: Defines the style for the button.
  • FocusNode? focusNode: Focus node of the widget.
  • bool autofocus: Whether this widget will be selected as initial focus. Defaults to false
  • Clip clipBehavior: Defines how the content is clipped. Defaults to Clip.none.
  • MaterialStatesController? statesController: Represents the MaterialState of the widget.
  • required Widget icon: Widget to be set as the icon.
  • required Widget label: Widget to be set as the label.

You can also read about: