multi-touch-canvas-with-flutter
Learn how to create a Flutter canvas with multi-touch support for panning, zooming, and object interaction, overcoming common gesture recognition conflicts.
What this skill does
# Multi-touch Canvas with Flutter
If you ever wanted to create a canvas in [Flutter](https://flutter.dev/) that needs to be panned in any direction and allow zoom then you also probably tried to create a [MultiGestureRecognizer](https://api.flutter.dev/flutter/gestures/MultiDragGestureRecognizer-class.html) or under a [GestureDetector](https://api.flutter.dev/flutter/widgets/GestureDetector-class.html) added onPanUpdate and onScaleUpdate and received an error because both can not work at the same time. Even if you have to GestureDetectors then you will still find it does not work how you want and one will always win.
> **TLDR** The final source [here](https://github.com/rodydavis/flutter_multi_touch_canvas) and an online [demo](https://rodydavis.github.io/flutter_multi_touch_canvas/).
This is the canvas rendering logic used in [https://widget.studio](https://widget.studio/)
## Multi Touch Goal
* Pan the canvas with two or more fingers
* Zoom the canvas with two fingers only (Pinch/Zoom)
* Single finger will interact with canvas object and detect selection
* Bonus trackpad support with similar results
In order to achieve this we need to use a Listener for the trackpad events and raw touch interactions and [RawKeyboardListener](https://api.flutter.dev/flutter/widgets/RawKeyboardListener-class.html) for keyboard shortcuts.
## Part 1 - Project Setup
Open your terminal and type the following:
```
mkdir flutter_multi_touch
cd flutter_multi_touch
flutter create .
code .
```
The last line is optional and if you have VSCode installed. The command will open the directory inside VSCode.
## Part 2 - Boilerplate
* Remove all comments
* Remove extra empty lines
* Update UI
Right now when you run the project you will have this UI.
Create a new file located at `ui/home/screen.dart` and add the following:
```
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
```
Update `main.dart` with the following:
```
import 'package:flutter/material.dart';
import 'ui/home/screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
darkTheme: ThemeData.dark().copyWith(
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeScreen(),
);
}
}
```
You will now have a black screen when you run the application.
## Part 3 - Creating the Controller
Now we want to create a class that will act as our controller on the canvas.
Create a new file at `src/controllers/canvas.dart` and add the following to start:
```
import 'dart:async';
/// Control the canvas and the objects on it
class CanvasController {
// Controller for the stream output
final _controller = StreamController<CanvasController>();
// Reference to the stream to update the UI
Stream<CanvasController> get stream => _controller.stream;
// Emit a new event to rebuild the UI
void add([CanvasController val]) => _controller.add(val ?? this);
// Stop the stream and finish
void close() => _controller.close();
// Start the stream
void init() => add();
}
```
Update the home screen with the following:
```
import 'package:flutter/material.dart';
import '../../src/controllers/canvas.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _controller = CanvasController();
@override
void initState() {
_controller.init();
super.initState();
}
@override
void dispose() {
_controller.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<CanvasController>(
stream: _controller.stream,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Scaffold(
appBar: AppBar(),
body: Center(child: CircularProgressIndicator()),
);
}
final instance = snapshot.data;
return Scaffold(
appBar: AppBar(),
body: Stack(
children: [
Positioned(
top: 20,
left: 20,
width: 100,
height: 100,
child: Container(color: Colors.red),
)
],
),
);
});
}
}
```
Here we are just adding the basics to rebuild when the controller changes or the screen is finished. We are using a stateful widget here because we want to dispose of the controller and load it only once. We are also using a stack because thats all we need under the hood. After a quick hot restart you should have the following view.
## Part 4 - Adding Canvas Objects
Now we need to create the class for the objects that will be stored on the canvas. Create a new file at `src/classes/canvas_object.dart` and add the following:
```
import 'dart:ui';
class CanvasObject<T> {
final double dx;
final double dy;
final double width;
final double height;
final T child;
CanvasObject({
this.dx = 0,
this.dy = 0,
this.width = 100,
this.height = 100,
this.child,
});
CanvasObject<T> copyWith({
double dx,
double dy,
double width,
double height,
T child,
}) {
return CanvasObject<T>(
dx: dx ?? this.dx,
dy: dy ?? this.dy,
width: width ?? this.width,
height: height ?? this.height,
child: child ?? this.child,
);
}
Size get size => Size(width, height);
Offset get offset => Offset(dx, dy);
Rect get rect => offset & size;
}
```
We are using a generic here to not depend on flutter or material in the class. Update the controller with the following:
```
import 'dart:async';
import 'package:flutter/material.dart';
import '../classes/canvas_object.dart';
/// Control the canvas and the objects on it
class CanvasController {
/// Controller for the stream output
final _controller = StreamController<CanvasController>();
/// Reference to the stream to update the UI
Stream<CanvasController> get stream => _controller.stream;
/// Emit a new event to rebuild the UI
void add([CanvasController val]) => _controller.add(val ?? this);
/// Stop the stream and finish
void close() => _controller.close();
/// Start the stream
void init() => add();
// -- Canvas Objects --
final List<CanvasObject<Widget>> _objects = [];
/// Current Objects on the canvas
List<CanvasObject<Widget>> get objects => _objects;
/// Add an object to the canvas
void addObject(CanvasObject<Widget> value) => _update(() {
_objects.add(value);
});
/// Add an object to the canvas
void updateObject(int i, CanvasObject<Widget> value) => _update(() {
_objects[i] = value;
});
/// Remove an object from the canvas
void removeObject(int i) => _update(() {
_objects.removeAt(i);
});
void _update(void Function() action) {
action();
add(this);
}
}
```
We are just adding the objects to the canvas and removing them if needed. Update the home screen with the following to use these new objects:
```
import 'package:flutter/material.dart';
import '../../src/classes/canvas_object.dart';
import '../../src/controllers/canvas.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _controller = CanvasControlRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.