Raised Button is our main widget to create buttons in Flutter. Raised button has its own onClick method known as onPressed. We can pass any function here in onPressed event and that particular function will called on button onPress event. We cannot set onPressed empty we should have pass something here like a function our inline function body code. So in this tutorial we would Set OnClick onPress event on Raised Button in Flutter Android iOS.
Contents in this project Set OnClick onPress event on Raised Button in Flutter Android iOS App Example Tutorial:
1. Import material.dart package in your app’s main.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Call our main MyApp class using void main runApp method.
1 |
void main() => runApp(MyApp()); |
3. Create a class named as MyApp extends with StatelessWidget. This is our main view class.
1 2 3 |
class MyApp extends StatelessWidget { } |
4. Create a function named as sampleFunction() in your MyApp class. We would call this function on button onPress event. We are printing a simple message on Command Prompt Terminal screen using print() method of dart.
1 2 3 4 5 |
sampleFunction(){ print('Function on Click Event Called.'); // Put your code here, which you want to execute on onPress event. } |
5. Create a Raised Button Widget in Column widget as children.
- onPressed : Call here the function here which we would created before.
1 2 3 4 5 6 7 8 |
RaisedButton( child: Text(" Button With OnPress "), onPressed: sampleFunction, color: Colors.red, textColor: Colors.white, splashColor: Colors.grey, padding: EdgeInsets.fromLTRB(10, 10, 10, 10), ) |
6. 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 30 31 32 33 34 35 36 37 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { sampleFunction(){ print('Function on Click Event Called.'); // Put your code here, which you want to execute on onPress event. } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:[ RaisedButton( child: Text(" Button With OnPress "), onPressed: sampleFunction, color: Colors.red, textColor: Colors.white, splashColor: Colors.grey, padding: EdgeInsets.fromLTRB(10, 10, 10, 10), ) ], ) ) ) ); } } |
Screenshot:

nice examples bro… I use these techniques for own work…
Thanks for comment Manprit 🙂 .