Buttons in Flutter

Types of button

In Flutter, a “button widget” refers to the various types of widgets that allow users to trigger actions by tapping on them. Flutter provides several built-in button widgets, each with its own styling and behavior. Here are some commonly used button widgets in Flutter:

  1. ElevatedButton: This is a Material Design raised button. It’s used for prominent actions in your app. It displays an ink splash when touched. You can customize its appearance using the style property.
ElevatedButton(
  onPressed: () {
    // Add your action here
  },
  child: Text('Text Button'),
)
  1. TextButton: This is a Material Design flat button. It’s used for less prominent actions. It also displays an ink splash when touched.
TextButton(
  onPressed: () {
    // Add your action here
  },
  child: Text('Text Button'),
)
  1. OutlinedButton: This is a Material Design outlined button. It’s used for more subtle actions and usually appears in combination with elevated buttons to indicate secondary actions.
OutlinedButton(
  onPressed: () {
    // Add your action here
  },
  child: Text('Outlined Button'),
)
  1. IconButton: This is a button widget that displays an icon. It’s often used for actions that can be represented with an icon.
IconButton(
  onPressed: () {
    // Add your action here
  },
  icon: Icon(Icons.star),
)
FlatButton: This is a deprecated button style as of Flutter 2.0. It was used for flat buttons with no elevation.

For example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Container'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: ElevatedButton(
          child: Text('Click Me'),
          onPressed: () {
            print('Hello World');
          },
          onLongPress: () {
            print('Hello World long press');
          },
        )
    );
  }
}