Mastering Resizable & Draggable Boxes with Flutter Box Transform
Table of Contents 6 sections
Creating an intuitive and user-friendly interface is an essential part of crafting exceptional user experiences. One such interface element commonly used across various applications is a resizable and draggable box. This component is particularly useful in the context of image manipulation tasks, such as cropping an image or adjusting its dimensions. Implementing a resizable box comes with its challenges, especially when it must accommodate advanced features like aspect ratio preservation, symmetric scaling, and cursor tolerance.
In this tutorial, we will dive into implementing our own resizable box and explore how to build a seamless, Figma-inspired crop UI using the power of Flutter Box Transform. By leveraging the capabilities of this package, you’ll be able to create an aesthetically refined and functionally robust draggable and resizable box that suits your application’s requirements in just a matter of minutes.
Throughout this tutorial, we will guide you step-by-step on how to incorporate advanced resizing mechanics, add customizable handle designs, manage various interactions, and ultimately create a user-friendly crop overlay UI that lives up to your users’ expectations.
So, let’s embark on this journey to transform your Flutter application with the remarkable potential of Flutter Box Transform.
flutter_box_transform | Flutter packageA Flutter implementation of box_transform package that provides easy 2D box transform operations with advanced resizing of rect in UI.pub.dev
How Figma does it
Let’s first observe Figma’s own selection box overlay and break down all of its advanced features:

Figma uses square-shaped corner handles and a thin border around the selected object. The corner handles have a white center with a border with the same blue color as the border around the entire selection.

The crop UI uses a variation that includes side handles as well, while the corner handles transform into short angular handles.

When you modify the crop region, the original image stays behind in faded form without resize handles, but stays draggable. The crop overlay, on the other hand, is not draggable, rather only resizable.
The resizing mechanics
Common to both the selection box and the crop overlay is the resizing mechanisms behind them that makes Figma’s UI/UX so pleasant to work with.
To ensure a comfortable user experience, the resizable box must incorporate some essential mechanics that users expect:
- Aspect Ratio Preservation: Users should be able to hold down the shift key to scale-resize the box to preserve its aspect ratio. This feature allows for precise adjustments while maintaining desired proportions.
- Symmetrical Resizing: Holding down the Option/Alt key should enable symmetrical resizing, where the cursor’s movements are mirrored. This functionality allows users to achieve balanced and uniform adjustments effortlessly.
- Symmetric-Scale Resizing: By holding down both keys simultaneously, users can perform symmetric-scale resizing, where both aspect ratio preservation and symmetrical resizing occur simultaneously. This feature offers a convenient way to achieve consistent modifications from multiple angles.
- Cursor Tolerance Area: For accessibility, the resizable box should provide a tolerance area around the handles. This area allows users to resize the box even if the cursor is not precisely touching the handle’s pixels. It alleviates the need for cursor precision and ensures a smoother resizing experience.
- Content flipping: When the cursor goes beyond the legal size of the box at certain key points, the content of the box should flip and the box grows in the opposite direction at an opposing anchor point. This has nothing to do with crop UIs, but rather is a general utility that designers use frequently.
- Moreover, it’s crucial to maintain a continuous connection between the box and the cursor throughout the entire operation. Disallowing the box from shrinking too quickly or moving away from the cursor during scale-resizing enhances the overall usability of the crop overlay UI.
Implementing these seemingly small features may appear trivial or even needlessly pedantic, but they significantly contribute to a polished and user-friendly experience.
Thanks to the power of the Flutter Box Transform package, incorporating these mechanics into your Flutter application becomes remarkably simple as its all done out of the box- pardon; inside the box- for you.
Building the crop UI
Now, let’s continue with a practical implementation of the crop overlay UI using Flutter Box Transform.
Setup
Let’s start by adding flutter_box_transform to our dependencies. Please check for the latest version on the pub.dev page:
dependencies:
flutter:
sdk: flutter
flutter_box_transform: ^latestNow let’s make a skeleton app that we want to work in:
import 'package:flutter/material.dart';
import 'package:flutter_box_transform/flutter_box_transform.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Box Transform Figma Replica',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
brightness: Brightness.dark,
),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold();
}
}The TransformableBox
Flutter Box Transform offers a Widget called a TransformableBox that does most of the work out of the box for us. Under the hood, it is a Positioned widget and must be placed as a direct descendant of a Stack widget.
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
TransformableBox(
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
// TODO: Render a pretty box.
},
),
],
),
);
}
}The contentBuilder controls what content is rendered inside of the box. For this tutorial, we will use a simple static image. We will also render a border that will later on change its color and width depending on if we are in a “crop” state.
TransformableBox(
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
),
image: const DecorationImage(
image: AssetImage('assets/image.png'),
fit: BoxFit.fill,
),
),
);
},
),Giving the box a starting position
Now, let’s tackle an important issue that’s keeping our box from shining its brightest. Currently, it might look like a lost circle or a lone ranger hiding in the top-left corner. Poor thing! The problem is that our TransformableBox doesn’t have a clue about its size and position. It’s like trying to dance without knowing the steps!
We’ll start by giving our TransformableBox a fresh start with a default state. Let’s give it a predefined Rect through the rect constructor parameter.
And that’s not all, we’ll keep our box in the loop by using the onChanged constructor parameter. This way, our box will stay updated with all the user’s actions and input that are handled internally by the TransformableBox widget itself.
class _MyHomePageState extends State<MyHomePage> {
late Rect rect = Rect.fromCenter(
center: MediaQuery.of(context).size.center(Offset.zero),
width: 400,
height: 300,
); // Initial State
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
TransformableBox(
rect: rect,
onChanged: (result, event) {
setState(() {
rect = result.rect;
});
},
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary,
),
image: const DecorationImage(
image: AssetImage('assets/image.png'),
fit: BoxFit.fill,
),
),
);
},
),
],
),
);
}
}
Congratulations! It’s a box! Note that if you dislike this pattern, TransformableBox fully supports Flutter’s controller pattern using a TransformableBoxController. For more information on that, head over to our documentation on it here:
When it comes to creating a formal system, you’d typically start with the box’s initial size, which can match the image itself or the size of your image editor. The box’s position would be set to (0, 0), representing a state where the entire image is selected.
Styling it like Figma
Anyways, time to Figmafy it!
TransformableBox(
key: const ValueKey('Main TransformableBox'),
rect: rect,
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue,
width: 2,
),
image: const DecorationImage(
image: AssetImage('assets/image.png'),
fit: BoxFit.fill,
),
),
);
},
visibleHandles: {
...HandlePosition.corners, // Convenient list that contains only corner handles.
},
cornerHandleBuilder: (context, handle) => DefaultCornerHandle(
handle: handle,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.blue,
width: 2,
),
),
),
),
Now that’s more like it!
Adding crop mode
We got the rendering to be identical using the flexible api offered by the TransformableBox! Now, for the crop UI, there are actually two boxes as observed earlier. One that is draggable and faded but not resizable, and the other is the actual crop region that is resizable but not draggable.
To replicate this, when entering the cropping mode, we will disable resizing on this TransformableBox and overlay a faded color, then spawn a new TransformableBox for the crop region and use Angular handles which are already built into the package for convenience!
In Figma, the side handles are not displayed unless you’re in cropping mode. So, for a cleaner look, we’ll hide the side handles and instead show angular corner handles when in cropping mode. We’ll also use Figma’s color scheme to ensure everything blends seamlessly.
In addition, we’ll also disable the handles on the main TransformableBox when cropping is enabled and set its border to a thin gray box.
class _MyHomePageState extends State<MyHomePage> {
bool cropping = false;
late Rect rect = Rect.fromCenter(
center: MediaQuery.of(context).size.center(Offset.zero),
width: 400,
height: 300,
);
late Rect cropRect = rect;
@override
Widget build(BuildContext context) {
return Scaffold(
// Enable and disable crop mode.
floatingActionButton: FloatingActionButton(
tooltip: cropping ? 'Disable cropping' : 'Enable cropping',
onPressed: () {
setState(() {
cropping = !cropping;
cropRect = rect;
});
},
child: Icon(cropping ? Icons.crop : Icons.crop_free),
),
body: Stack(
fit: StackFit.expand,
children: [
TransformableBox(
key: const ValueKey('Main TransformableBox'),
rect: rect,
onChanged: (result, event) {
setState(() {
rect = result.rect;
});
},
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: cropping ? Colors.grey : Colors.blue, // Aesthetic change when cropping
width: cropping ? 0.75 : 2, // Aesthetic change when cropping
),
image: DecorationImage(
image: const AssetImage('assets/image.png'),
fit: BoxFit.fill,
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(!cropping ? 0 : 0.5), // Aesthetic change when cropping
BlendMode.hardLight,
),
),
),
);
},
visibleHandles: {
if (!cropping) // Returns an empty set when in cropping mode.
...HandlePosition.corners,
},
enabledHandles: {
if (!cropping) // Returns an empty set when in cropping mode.
...HandlePosition.corners,
},
cornerHandleBuilder: (context, handle) => DefaultCornerHandle(
handle: handle,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.blue,
width: 2,
),
),
),
),
if (cropping) // The crop region that is inserted only when cropping is enabled.
TransformableBox(
key: const ValueKey('Crop Region TransformableBox'),
rect: cropRect,
allowContentFlipping: false,
onChanged: (result, event) {
setState(() {
cropRect = result.rect;
});
},
contentBuilder: (BuildContext context, Rect rect, Flip flip) {
return Stack(
children: [
// A debug box.
// const Positioned.fill(child: ColoredBox(color: Colors.red)),
Positioned.fromRect(
rect: Rect.fromCenter(
center: this.rect.center - rect.topLeft,
width: this.rect.width,
height: this.rect.height,
), // Matches the position of the original rect visually only.
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 0.75,
),
image: const DecorationImage(
image: AssetImage('assets/image.png'),
fit: BoxFit.fill,
),
),
),
)
],
);
},
cornerHandleBuilder: (context, handle) => AngularHandle(
handle: handle,
color: Colors.blue,
hasShadow: false,
length: 16,
),
sideHandleBuilder: (context, handle) => AngularHandle(
handle: handle,
color: Colors.blue,
hasShadow: false,
length: 16,
),
),
],
),
);
}
}Wow, we’re basically done! So what changed? Let’s break it down!
- We introduced a new boolean variable called “cropping” to keep track of the crop mode. To enable or disable cropping, simply tap on the floating action button.
- The border decoration has been adjusted to have a thinner border and a gray color, just like in Figma when cropping is enabled.
- When cropping is enabled, all the handles become disabled. We achieved this by returning an empty set in the
visibleHandles&enabledHandlesconstructor parameters. - When cropping is enabled, we spawn a new
TransformableBoxwith the same dimensions as the current main rectangle. Inside this new box, we use theAngularHandlewidget with custom parameters. Custom widgets are supported as well. TheAngularHandleis a convenient handle widget built directly in the package as it’s a very common use case. - When cropping is enabled, we apply a hard-light color filter over the image. Another approach would be to use a Stack inside the content builder and overlay a
ColoredBoxto achieve the same effect. - As for the crop region’s
TransformableBox, we ensure that the content doesn’t flip and renders the same image in full color. It is positioned based on the placement of the main rectangle using some transformation math.
You may wish to not render any content inside the crop-region’s TransformableBox and allow it to be transparent/see-through instead of double-rendering the content and applying some transformation math. That is easily possible, however, you will need to use a CustomClipper or CustomPainter to render a subtracted gray/faded region over the main TransformableBox without leaking inside the crop region.
There are multiple ways to do this in Flutter, but for the sake of this tutorial, we will keep to this methodology.
Advanced Usage #1: Ensuring the crop region stays within the bounds of the main rectangle
In Figma, you have the flexibility to move the crop region outside the content area. However, if you prefer to restrict the crop region within the bounds, similar to what most social media apps do, you can easily achieve that by setting the clampingRect parameter in your crop region to be the same as your main TransformableBox’s rectangle. Here’s an example of how you can do it:
if (cropping)
TransformableBox(
key: const ValueKey('Crop Region TransformableBox'),
rect: cropRect,
clampingRect: rect, // <--
allowContentFlipping: false,
onChanged: (result, event) {
setState(() {
cropRect = result.rect;
});
},Advanced Usage #2: Adjusting drag behavior
When implementing a crop UI, you might want to deny movement of the main rectangle while allowing only the crop rectangle to be movable. Achieving this is straightforward: you just need to set the draggable parameter to false. Here’s an example:
TransformableBox(
key: const ValueKey('Main TransformableBox'),
rect: rect,
draggable: false, // <--
onChanged: (result, event) {
setState(() {
rect = result.rect;
});
},
);In some crop UI designs, the crop region remains fixed while the image itself is draggable and resizable. In this case, you can set the draggable constructor parameter to false for the crop region and keep it set to true for the main TransformableBox.
Final Notes
- The
flutter_box_transformpackage offers incredible flexibility and customization options. You can customize how shortcuts are handled, including disabling them altogether. It’s also possible to enforce a singleResizeModeif desired, such as always using scaling. - You have the choice to disallow the box from flipping or allow it to flip while keeping only the content unflippable.
- Instead of using a clamping rectangle, you can provide
BoxConstraintsto restrict the size of yourTransformableBoxwithin desired limits.BoxConstraintsenable setting minimum & maximum sizing restrictions, but do not provide restrictions on the position of your box. - There are detailed resize and drag event callbacks available, including terminal events that notify you when your box reaches a hard limit during resizing. These callbacks are all available within the constructor of the
TransformableBoxwidget. - The
TransformableBoxfully supports Flutter’s controller pattern. If desired, you can use aTransformableBoxControllerto programmatically control yourTransformableBoxexternally. - If you need to handle box resizing programmatically without depending on Flutter, you can use the core
box_transformpackage thatflutter_box_transformbuilds on. It offers the same mechanisms but without depending on Flutter. You can use it in isolates, server environments, or any place that cannot rely on Flutter.
Resources
Check out the playground we built for this package to explore all of its features in full!
Box Transform PlaygroundEvery Box Transform feature, live in the browser: resize, drag, flip, constrain and crop.box-transform-playground.firebaseapp.comIf you need detailed instructions on how to use the package, please read our exhaustive documentation:
Box TransformEasily create the best possible resizable and draggable boxes for your project.boxtransform.hyperdesigned.dev
Feel free to join our Discord server for any inquiries or support. We’d be happy to help you out!
Join the Hyperdesigned Discord Server!The official Hyperdesigned discord server for all projects produced by the Hyperdesigned team. | 49 membersdiscord.ggHere’s the complete app we built:
Box Transform Figma ReplicaBox Transform Figma Replica. GitHub Gist: instantly share code, notes, and snippets.gist.github.com