Learn how to handle Gestures in an app using GestureDetector in flutter.
Example 1: Simple GestureDetector Example
Start learning and using GestureDetector using this simple one-file example.
Step 1: Create Project
Start by creating an empty Flutter Project in your favorite editor or IDE.
Step 2: Add Dependencies
No external packages are needed for this project.
Step 3: Write Code
Here is how you build a box able of detecting Gestures using GestureDetector in flutter:
class Box extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorState = ColorState.of(context);
return GestureDetector(
onTap: colorState.onTap,
//onVerticalDragUpdate: (d) => print('dragging vertical'),
//onHorizontalDragUpdate: (d) => print('dragging horizontal'),
child: Container(
width: 50.0,
height: 50.0,
margin: EdgeInsets.only(left: 100.0),
color: colorState.color,
),
);
}
}
Here is the full code:
main.dart
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MaterialApp(
title: "Random Squares",
home: MyApp(),
));
class MyApp extends StatefulWidget {
@override
AppState createState() => AppState();
}
class AppState extends State<MyApp> {
final Random _random = Random();
Color color = Colors.amber;
void onTap() {
setState(() {
color = Color.fromRGBO(
_random.nextInt(256),
_random.nextInt(256),
_random.nextInt(256),
_random.nextDouble(),
);
});
}
@override
Widget build(BuildContext context) {
return ColorState(
color: color,
onTap: onTap,
child: BoxTree(),
);
}
}
class ColorState extends InheritedWidget {
ColorState({
Key key,
this.color,
this.onTap,
Widget child,
}) : super(key: key, child: child);
final Color color;
final Function onTap;
@override
bool updateShouldNotify(ColorState oldWidget) {
return color != oldWidget.color;
}
static ColorState of(BuildContext context) {
return context.inheritFromWidgetOfExactType(ColorState);
}
}
class BoxTree extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: <Widget>[
Box(),
Box(),
],
),
),
);
}
}
class Box extends StatelessWidget {
@override
Widget build(BuildContext context) {
final colorState = ColorState.of(context);
return GestureDetector(
onTap: colorState.onTap,
//onVerticalDragUpdate: (d) => print('dragging vertical'),
//onHorizontalDragUpdate: (d) => print('dragging horizontal'),
child: Container(
width: 50.0,
height: 50.0,
margin: EdgeInsets.only(left: 100.0),
color: colorState.color,
),
);
}
}
Run
Copy the code into your project or download the code in the reference links below.
Reference
Find the reference links below:
Number | Link |
---|---|
1. | Download code |
2. | Follow code author |