Flutter Button on Long Press
In this tutorial, we will learn to execute a function when user long presses a button.
To execute a set of instructions for long-press action, use onLongPress property.
We shall use RaisedButton for a button. The working should be same even for other types of Buttons.
Sample Code Snippet
Following is a sample code snippet to use onLongPress property with RaisedButton.
RaisedButton(
onLongPress: () => {
//do something
},
child: new Text('Click me'),
),
Example
This is an example Flutter Application to demonstrate on how to respond for long press action on a button.
To recreate this example, create an empty Flutter Application and replace main.dart with the following code.
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => new _State();
}
class _State extends State<MyApp> {
int count = 0;
void incrementCounter() {
setState(() {
count++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Flutter Tutorial - googleflutter.com'),
),
body: new Center(
child: new RaisedButton(
onLongPress: () => {
incrementCounter()
},
child: new Text('Button Clicks - ${count}'),
),
),
);
}
}
When you run this Flutter application, the following UI should be displayed in the mobile. When you long press on the button, we shall increment the count in the button.
Summary
In this Flutter Tutorial, we learned how to respond for a long press on a button.