Episode 11: Mastering Elevated Button in Flutter: A Complete Guide
Season 1: Exploring Common Widgets #flutterforbeginners
What is an ElevatedButton?
The ElevatedButton is a Material Design raised button, which means it's a label displayed on a Material widget that elevates when pressed—giving a delightful interactive feel. This visual feedback contributes to a more intuitive user interface, enhancing the user experience.
How to Use an ElevatedButton?
Incorporating an ElevatedButton into your Flutter application is quite straightforward. For instance, if you wish to add a button to the Scaffold's body that simply prints a message on being pressed, the following code snippet does just that:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Mastering ElevatedButton in Flutter'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
print('Button pressed');
},
child: Text('Press me'),
),
),
),
);
}
}
Customizing ElevatedButton
ElevatedButton allows for extensive customization. With properties such as 'style', you can alter the button's appearance—its background color, padding, minimum size, and more. Here's how you can style your button:
ElevatedButton(
onPressed: () {
print('Button pressed');
},
child: Text('Press me'),
style: ElevatedButton.styleFrom(
primary: Colors.green,
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 20),
minimumSize: Size(200, 50),
),
)
The 'onPressed' function can also control whether the button is enabled or not. By passing null to 'onPressed', the button becomes disabled and appears greyed out.
ElevatedButton with Icons
You might often want to include an icon along with text in your button. This is achieved using the ElevatedButton.icon constructor, as demonstrated below:
ElevatedButton.icon(
onPressed: () {
print('Button pressed');
},
icon: Icon(Icons.mail),
label: Text('Mail me'),
style: ElevatedButton.styleFrom(
primary: Colors.green,
),
)
With Flutter's ElevatedButton, creating interactive, responsive, and stylish buttons is a breeze. Experiment with different styles and layouts to create the perfect button for your application.
Stay tuned for more insights into Flutter's vast library of widgets! We're here to assist you in your Flutter journey, and we're excited to see what you create with Flutter's ElevatedButton.