Hello friends, As you all know I’m trying to cover Elevated Button widget in flutter with small small examples. In today’s example tutorial we would learn about How in Flutter Set onPressed onClick on Elevated Button. Elevated button is a good alternative option after deprecation of Raised button in flutter. So let’s get started 🙂 .
Contents in this project Flutter Set onPressed onClick on Elevated Button in Android iOS Example :-
1. Open your flutter project’s main.dart file and import material.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Creating void main runApp() method and here we would call our main MyApp widget.
1 |
void main() => runApp(MyApp()); |
3. Creating our main class MyApp extends StatelessWidget. This is our main Parent class.
1 2 3 4 5 |
class MyApp extends StatelessWidget { } |
4. Creating a sample function named as printMSG(). We would call this message on button click onPress event. In this function we would simply print a console message on terminal window.
1 2 3 |
void printMSG() { print('Elevated Button Clicked...'); } |
5. Creating Widget Build Area -> Material App -> Scaffold Widget -> Center Widget -> Container Widget.
1 2 3 4 5 6 7 8 9 10 |
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Container( margin: const EdgeInsets.all(10), child: ), ))); } |
6. Now we would create the ElevatedButton widget as child of Container widget. Here you can see we are using onPressed method to set click event on elevated button.
1 2 3 4 5 6 7 8 9 |
ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.lightBlue, padding: EdgeInsets.all(12), textStyle: TextStyle(fontSize: 22), ), child: Text('Elevated Button With OnPress'), onPressed: printMSG, ), |
7. Complete source code for main.dart file :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { void printMSG() { print('Elevated Button Clicked...'); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Container( margin: const EdgeInsets.all(10), child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.lightBlue, padding: EdgeInsets.all(12), textStyle: TextStyle(fontSize: 22), ), child: Text('Elevated Button With OnPress'), onPressed: printMSG, ), ), ))); } } |
Screenshots:-
