Working with ElevatedButton in Flutter (2021)

Last updated on August 13, 2021 A Goodman Loading... 9 comments

Most mobile and web applications have buttons that allow users to press to interact with. In Flutter, you can use the ElevatedButton widget to create elevated buttons.

ElevatedButton is the replacement for RaisedButton which is obsolete.

Note: To use ElevatedButton without warnings or errors, you should update to Flutter 1.22.0 or higher versions. The simplest way to do that is to run this command: flutter upgrade

This tutorial will guide you through implementing elevated buttons as well as styling them.

What is an ElevatedButton in Flutter?

An ElevatedButton is a label child displayed on a Material widget whose Material.elevation increases when the button is pressed. The label’s Text and Icon widgets are displayed in style’s ButtonStyle.foregroundColor and the button’s filled background is the ButtonStyle.backgroundColor.

Constructors

ElevatedButton:

ElevatedButton({
  Key? key, 
  required VoidCallback? onPressed, 
  VoidCallback? onLongPress, 
  ButtonStyle? style, 
  FocusNode? focusNode, 
  bool autofocus = false, 
  Clip clipBehavior = Clip.none, 
  required Widget? child
})

ElevatedButton with icon:

ElevatedButton.icon({
  Key key, 
  @required VoidCallback onPressed, 
  VoidCallback onLongPress, 
  ButtonStyle style, 
  FocusNode focusNode, 
  bool autofocus, 
  Clip clipBehavior, 
  @required Widget icon, 
  @required Widget label
})

Basic example:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(25),
          child: Column(children: [
            ElevatedButton(onPressed: () {}, child: Text('I gotta pee')),
            ElevatedButton.icon(
              onPressed: () {},
              label: Text('Plus One'),
              icon: Icon(Icons.plus_one),
            )
          ]),
        ));
  }
}

Output:

Enable/Disable

To disable an ElevatedButton, just set the onPressed parameter to null. To enable an ElevatedButton, set the onPressed parameter to a void function.

Example:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            // An enabled button
            ElevatedButton(
              child: Text('Enabled Button'),
              onPressed: () {},
            ),

            // A disabled button
            ElevatedButton(onPressed: null, child: Text('Disabled Button'))
          ],
        ),
      ),
    );
  }
}

Output:

Style (Color, Border, Elevation…)

You can style ElevatedButton by using the styleFrom static method or the ButtonStyle class. The first one is more convenient than the second one.

Using styleFrom to style an ElevatedButton:

ElevatedButton(
      child: Text('Button'),
      onPressed: () {},
      styleFrom({
          Color? primary, // Use this to set the background color
          Color? onPrimary, 
          Color? onSurface, 
          Color? shadowColor, 
          double? elevation, 
          TextStyle? textStyle, 
          EdgeInsetsGeometry? padding, 
          Size? minimumSize, 
          Size? fixedSize, // Use this for sizing the button
          BorderSide? side, 
          OutlinedBorder? shape, // Button shape
          MouseCursor? enabledMouseCursor, 
          MouseCursor? disabledMouseCursor, 
          VisualDensity? visualDensity, 
          MaterialTapTargetSize? tapTargetSize, 
          Duration? animationDuration, 
          bool? enableFeedback, 
          AlignmentGeometry? alignment, 
          InteractiveInkFeatureFactory? splashFactory
      })
),

Example:

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ElevatedButton.styleFrom(
                primary: Colors.purple,
                padding: EdgeInsets.symmetric(horizontal: 50, vertical: 20),
                textStyle: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.bold)),
),

Output:

Using ButtonStyle to style an ElevatedButton:

ButtonStyle({
  MaterialStateProperty<TextStyle?>? textStyle, 
  MaterialStateProperty<Color?>? backgroundColor, 
  MaterialStateProperty<Color?>? foregroundColor, 
  MaterialStateProperty<Color?>? overlayColor, 
  MaterialStateProperty<Color?>? shadowColor, 
  MaterialStateProperty<double?>? elevation, 
  MaterialStateProperty<EdgeInsetsGeometry?>? padding, 
  MaterialStateProperty<Size?>? minimumSize, 
  MaterialStateProperty<Size?>? fixedSize, 
  MaterialStateProperty<BorderSide?>? side, 
  MaterialStateProperty<OutlinedBorder?>? shape, 
  MaterialStateProperty<MouseCursor?>? mouseCursor, 
  VisualDensity? visualDensity, 
  MaterialTapTargetSize? tapTargetSize, 
  Duration? animationDuration, 
  bool? enableFeedback, 
  AlignmentGeometry? alignment, 
  InteractiveInkFeatureFactory? splashFactory
})

Example:

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.red),
                padding: MaterialStateProperty.all(EdgeInsets.all(50)),
                textStyle: MaterialStateProperty.all(TextStyle(fontSize: 30))),
),

Output:

Width & Height

There are several ways to size an elevated button.

1. You can set the width and height for an elevated button exactly as you want by using the fixedSize parameter of the styleFrom static method like this:

 style: ElevatedButton.styleFrom(fixedSize: Size([width], [height])),

This code creates an elevated button with a width of 240 and a height of 80:

ElevatedButton(
     onPressed: () {},
     child: Text('240 x 80'),
          style: ElevatedButton.styleFrom(
            fixedSize: Size(240, 80), 
            primary: Colors.deepOrange
    ),
),

Output:

2. You can also set the width and height for an elevated button by wrapping it inside a ConstrainedBox widget.

The following sample code shows you how to make an elevated button with the size of 300 x 200:

Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: Center(
          child: ConstrainedBox(
            constraints: BoxConstraints.tightFor(width: 300, height: 200),
            child: ElevatedButton(
              child: Text('300 x 200'),
              onPressed: () {},
            ),
          ),
        ));
  }

Output:

You can learn more about ConstrainedBox in this article: Flutter ConstrainedBox – Tutorial and Examples.

Button Shape

You can custom the shape of an elevated button by using the shape parameter of the styleFrom method.

Example:

ElevatedButton(
          onPressed: () {},
          child: Text('Kindacode.com'),
          style: ElevatedButton.styleFrom(
              primary: Colors.pink,
              fixedSize: Size(300, 100),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(50))),
        ),

Output:

You can find more details about shaping a button in Flutter by having a glance at the following guides:

ElevatedButton Theme

You can use ElevatedButtonTheme classes to set the look and behavior of descendant elevated buttons. This helps you set the look and behavior of multiple elevated buttons at a time.

Example:

// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Kindacode.com',
        theme: ThemeData(
            primarySwatch: Colors.green,
            elevatedButtonTheme: ElevatedButtonThemeData(
                style: ElevatedButton.styleFrom(
                    primary: Colors.red,
                    padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
                    textStyle: TextStyle(
                      fontStyle: FontStyle.italic,
                      fontSize: 24,
                    )))),
        home: HomePage());
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(onPressed: () {}, child: Text('Button 1')),
            SizedBox(
              height: 30,
            ),
            ElevatedButton.icon(
                onPressed: () {},
                icon: Icon(Icons.play_arrow),
                label: Text('Play Video'))
          ],
        ),
      ),
    );
  }
}

Output:

Note that these settings can be overridden if you style each button individually as we did in the above sections.

Another Example

Preview:

Only ElevatedButton code:

ElevatedButton(
        style: ElevatedButton.styleFrom(
            // background color
            primary: Colors.orange,
            padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
            textStyle: TextStyle(fontSize: 20),
          ),
        child: Text('I am a button'),
        onPressed: () {
              print('Button clicked!');
        },
),

Full code in ./lib/main.dart:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Example'),
        backgroundColor: Colors.black,
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(children: [
          ////////////////////////
          /// Here's the button 
          ElevatedButton(
            style: ElevatedButton.styleFrom(
            // background color
            primary: Colors.orange,
            padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
            textStyle: TextStyle(fontSize: 20),
          ),
            child: Text('I am a button'),
            onPressed: () {
              print('Button clicked!');
            },
          ),
        ]),
      ),
    );
  }
}

Conclusion

This tutorial went over the basics of working with the ElevatedButton class in Flutter. You also explored several examples of how to implement, style, set background color, change text color, set width and height, etc, for an ElevatedButton.

Continue learning more about Flutter by taking a look at the following tutorials:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
9 Comments
Inline Feedbacks
View all comments
Jack
Jack
1 month ago

It’s good

Bad Boy
Bad Boy
1 month ago

Nice

Levi
Levi
2 months ago

Really helped. Thanks!!

Brady Holfin
Brady Holfin
5 months ago

Perfect article. Thank you.

Arshad
Arshad
5 months ago

thanks

Arsahd
Arsahd
5 months ago

Super..

bqubique
bqubique
5 months ago

thanks

kkc
kkc
6 months ago

super

trackback
Flutter TextButton example | Kindacode
11 months ago

[…] Related: FlutterElevatedButton example […]

Related Articles