How to set offset between feedback and pointer when using `Draggable` in flutter? - flutter

I'm trying to make fill-in-the-blank UI by using DragTarget and Draggable.
I want to set offset between feedback and pointer during dragging to prevent the feedback from beeing hidden by a finger,
and I need to do hit-testing between the feedback and the dragtarget
How can I implement this?
This is what I want to implement.
Solution
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _text = '';
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
child: Center(
child: _buildDragTarget(),
),
),
Expanded(
child: Center(
child: _buildDraggable(),
),
),
],
),
);
}
Widget _buildDragTarget() {
return DragTarget<String>(onAccept: (data) {
setState(() {
_text = data;
});
}, builder: (BuildContext context, List candidateData, List rejectedData) {
return Container(
width: 150,
height: 50,
decoration: BoxDecoration(
border: Border.all(width: 3, color: Colors.blue),
),
child: Center(
child: Text(
_text,
style: TextStyle(fontSize: 24),
),
),
);
});
}
Widget _buildDraggable() {
var draggable = Chip(
label: Text(
'draggable',
style: TextStyle(fontSize: 24),
),
);
var feedback = Transform.scale(
scale: 2.0,
child: Opacity(
opacity: 0.5,
child: Container(
padding: EdgeInsets.only(bottom: 100),
child: Material(
color: Colors.transparent,
child: Transform.scale(
scale: 0.5,
child: draggable,
)),
),
),
);
return Draggable<String>(
dragAnchor: DragAnchor.child,
child: draggable,
feedback: feedback,
feedbackOffset: Offset(0, -50),
data: 'draggable',
);
}
}
This is the result.

In this case, I would suggest using the Transform widget to scale up the selected draggable item by a bit and use it as feedback. It will also give the user a feel that the item has been picked up.
Just wrap your draggable widget with Transform and use scale property with value ~1.25. (an example value) This will increase the size of the widget by 25%.
However, if you specifically need to add an offset for the picked Item, then just use a padded version of the draggable item as feedback.
For example,
If you need to add move the draggable a bit above the current touch position, then just add required padding below the draggable item.
Basically, by adding some padding in the opposite side, it gives you an effect of adding offset in the widget.
I would still suggest going for the Transform widget approach. It feels more genuine and is common in all similar UIs.
If you have any questions about this approach, let me know in the comments.

An easier solution may be to add this function:
Offset myPointerDragAnchorStrategy(
Draggable<Object> draggable, BuildContext context, Offset position) {
return Offset(10, 0);
}
and then set the dragAnchorStrategy property in the Draggable object:
return Draggable<String>(
...
dragAnchorStrategy: myPointerDragAnchorStrategy,
...
);

Related

Use onPan GestureDetector inside a SingleChildScrollView

Problem
So I have a GestureDetector widget inside SingleChildScrollView (The scroll view is to accommodate smaller screens). The GestureDetector is listening for pan updates.
When the SingleChildScrollView is "in use" the GestureDetector cannot receive pan updates as the "dragging" input from the user is forwarded to the SingleChildScrollView.
What I want
Make the child GestureDetector have priority over the SingleChildScrollView when dragging on top of the GestureDetector -- but still have functionality of scrolling SingleChildScrollView outside GestureDetector.
Example
If you copy/paste this code into dart pad you can see what I mean. When the gradient container is large the SingleChildScrollView is not active -- you are able to drag the blue box and see the updates in the console. However, once you press the switch button the container becomes smaller and the SingleChildScrollView becomes active. You are now no longer able to get pan updates in the console only able to scroll the container.
Sidenote: It seems that if you drag on the blue box quickly you are able to get drag updates but slowly dragging it just scrolls the container. I'm not sure if that's a bug or a feature but I'm not able to reproduce the same result in my production app.
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({Key? key}) : super(key: key);
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
bool enabled = false;
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: enabled ? 200 : 400,
child: SingleChildScrollView(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment(0.8, 0.0),
colors: <Color>[Color(0xffee0000), Color(0xffeeee00)],
tileMode: TileMode.repeated,
),
),
height: 400,
width: 200,
child: Center(
child: GestureDetector(
onPanUpdate: (details) => print(details),
child: Container(
height: 100,
width: 100,
color: Colors.blue,
child: Center(
child: Text(
"Drag\nme",
textAlign: TextAlign.center,
),
),
),
),
),
),
),
),
ElevatedButton(
onPressed: () => setState(() {
enabled = !enabled;
}),
child: Text("Switch"))
],
);
}
}
As #PatrickMahomes said this answer (by #Chris) will solve the problem. However, it will only check if the drag is in line with the GestureDetector. So a full solution would be this:
bool _dragOverMap = false;
GlobalKey _pointerKey = new GlobalKey();
_checkDrag(Offset position, bool up) {
if (!up) {
// find your widget
RenderBox box = _pointerKey.currentContext.findRenderObject();
//get offset
Offset boxOffset = box.localToGlobal(Offset.zero);
// check if your pointerdown event is inside the widget (you could do the same for the width, in this case I just used the height)
if (position.dy > boxOffset.dy &&
position.dy < boxOffset.dy + box.size.height) {
// check x dimension aswell
if (position.dx > boxOffset.dx &&
position.dx < boxOffset.dx + box.size.width) {
setState(() {
_dragOverMap = true;
});
}
}
} else {
setState(() {
_dragOverMap = false;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Scroll Test"),
),
body: new Listener(
onPointerUp: (ev) {
_checkDrag(ev.position, true);
},
onPointerDown: (ev) {
_checkDrag(ev.position, false);
},
child: ListView(
// if dragging over your widget, disable scroll, otherwise allow scrolling
physics:
_dragOverMap ? NeverScrollableScrollPhysics() : ScrollPhysics(),
children: [
ListTile(title: Text("Tile to scroll")),
Divider(),
ListTile(title: Text("Tile to scroll")),
Divider(),
ListTile(title: Text("Tile to scroll")),
Divider(),
// Your widget that you want to prevent to scroll the Listview
Container(
key: _pointerKey, // key for finding the widget
height: 300,
width: double.infinity,
child: FlutterMap(
// ... just as example, could be anything, in your case use the color picker widget
),
),
],
),
),
);
}
}

Expanded with max width / height?

I want widgets that has certain size but shrink if available space is too small for them to fit.
Let's say available space is 100px, and each of child widgets are 10px in width.
Say parent's size got smaller to 90px due to resize.
By default, if there are 10 childs, the 10th child will not be rendered as it overflows.
In this case, I want these 10 childs to shrink in even manner so every childs become 9px in width to fit inside parent as whole.
And even if available size is bigger than 100px, they keep their size.
Wonder if there's any way I can achieve this.
return Expanded(
child: Row(
children: [
...List.generate(Navigation().state.length * 2, (index) => index % 2 == 0 ? Flexible(child: _Tab(index: index ~/ 2, refresh: refresh)) : _Seperator(index: index)),
Expanded(child: Container(color: ColorScheme.brightness_0))
]
)
);
...
_Tab({ required this.index, required this.refresh }) : super(
constraints: BoxConstraints(minWidth: 120, maxWidth: 200, minHeight: 35, maxHeight: 35),
...
you need to change Expanded to Flexible
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(appBar: AppBar(), body: Body()),
);
}
}
class Body extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: 80,
color: Colors.green,
child: Row(
children: List.generate(10, (i) {
return Flexible(
child: Container(
constraints: BoxConstraints(maxWidth: 10, maxHeight: 10),
foregroundDecoration: BoxDecoration(border: Border.all(color: Colors.yellow, width: 1)),
),
);
}),
),
);
}
}
two cases below
when the row > 100 and row < 100
optional you can add mainAxisAlignment property to Row e.g.
mainAxisAlignment: MainAxisAlignment.spaceBetween,
Try this
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 10,maxHeigth:10),
child: ChildWidget(...),
)
The key lies in a combination of using Flexible around each child in the column, and setting the child's max size using BoxContraints.loose()
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Make them fit',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int theHeight = 100;
void _incrementCounter() {
setState(() {
theHeight += 10;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Playing with making it fit'),
),
body: Container(
color: Colors.blue,
child: Padding(
// Make the space we are working with have a visible outer border area
padding: const EdgeInsets.all(8.0),
child: Container(
height: 400, // Fix the area we work in for the sake of the example
child: Column(
children: [
Expanded(
child: Column(
children: [
Flexible(child: SomeBox('A')),
Flexible(child: SomeBox('A')),
Flexible(child: SomeBox('BB')),
Flexible(child: SomeBox('CCC')),
Flexible(
child: SomeBox('DDDD', maxHeight: 25),
// use a flex value to preserve ratios.
),
Flexible(child: SomeBox('EEEEE')),
],
),
),
Container(
height: theHeight.toDouble(), // This will change to take up more space
color: Colors.deepPurpleAccent, // Make it stand out
child: Center(
// Child column will get Cross axis alighnment and stretch.
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text('Press (+) to increase the size of this area'),
Text('$theHeight'),
],
),
),
)
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class SomeBox extends StatelessWidget {
final String label;
final double
maxHeight; // Allow the parent to control the max size of each child
const SomeBox(
this.label, {
Key key,
this.maxHeight = 45,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ConstrainedBox(
// Creates box constraints that forbid sizes larger than the given size.
constraints: BoxConstraints.loose(Size(double.infinity, maxHeight)),
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
decoration: BoxDecoration(
color: Colors.green,
border: Border.all(
// Make individual "child" widgets outlined
color: Colors.red,
width: 2,
),
),
key: Key(label),
child: Center(
child: Text(
label), // pass a child widget in stead to make this generic
),
),
),
);
}
}

How to scale a Text widget that would behave like a scaling of an image

I would like to perform an Hero transition that will change, at the end, the size of a Widget.
This widget contains some text.
By default, the text widget will resize and the text inside move and resize to fit the text widget.
I would like to make to whole widget behave like an image would do : Everything will scale (zoom).
I tried :
auto_size_text package : The text will still move and the result is not perfect
screenshot package : It take too long to generate the image, replace the current widget with the image before performing the hero transition.
I am thinking about RenderRepaintBoundary, but this seems a lot of work for a simple task.
Any idea ?
If I understand what you want to achieve, you may want to use FittedBox.
This is what I used to create the animation below, where the Text widgets have a different size between the beginning and the end of the animation:
Thanks to #Romain, the easy answer was indeed FittedBox.
Making a Hero transition that will change the size of a Text Widget will be smooth when I put a FittedBox on the second page.
But I needed to pass down the original size to the second page to make the Text inside the FittedBox appear on the same number of lines that it was previously displayed.
Here the result :
https://vimeo.com/346745092
Here the code :
import 'package:flutter/material.dart';
const String textThatCouldChangeDependingOnContext = "Hero Text .... ";
main() {
runApp(MaterialApp(home: MyHomePage()));
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
GlobalKey _textKey = GlobalKey();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(64.0),
child: Column(
children: <Widget>[
Hero(
tag: 'tag',
child: Material(
child: Container(
color: Colors.red,
child: Text(textThatCouldChangeDependingOnContext,
key: _textKey),
),
),
),
FlatButton(
child: Text('Fly'),
onPressed: () {
Size originalTextSize = _textKey.currentContext.size;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
MySecondPage(originalTextSize)));
},
)
],
),
),
),
);
}
}
class MySecondPage extends StatefulWidget {
final Size originalTextSize;
MySecondPage(this.originalTextSize);
#override
_MySecondPageState createState() => _MySecondPageState();
}
class _MySecondPageState extends State<MySecondPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
onTap: () => Navigator.pop(context),
child: Hero(
tag: 'tag',
transitionOnUserGestures: true,
child: Material(
child: Container(
color: Colors.red,
child: FittedBox(
fit: BoxFit.contain,
child: SizedBox(
height: widget.originalTextSize.height,
width: widget.originalTextSize.width,
child: Text(textThatCouldChangeDependingOnContext),
),
),
),
),
),
)
],
),
),
);
}
}

How to create a carrousel (sliding animation) with PageView in Flutter?

I want to create slider animation with Images and also want to allow user to use swipe gesture to move back and forth. Another requirement is Page indicator. For this purpose, I used
page_indicator: ^0.1.3
Currently I am able to slide between images using swipe gesture with page indicator and now I want to animate slides repeatedly with x amount of duration.
My code is below.
final PageController controller = new PageController();
#override
Widget build(BuildContext context) {
List<Widget> list = new List<Widget>();
list.add(new SliderBox(image: 'assets/shirt.png'));
list.add(new SliderBox(image: 'assets/laptops.png'));
list.add(new SliderBox(image: 'assets/bags.png'));
PageIndicatorContainer container = new PageIndicatorContainer(
pageView: new PageView(
children: list,
controller: controller,
),
length: 3,
padding: EdgeInsets.fromLTRB(10, 40, 10, 10),
indicatorSpace: 10,
indicatorColor: Colors.grey[350],
indicatorSelectorColor: Colors.grey,
);
return Stack(children: <Widget>[
Container(color: Colors.grey[100], height: double.infinity),
Container(
color: Colors.white,
child: container,
margin: EdgeInsets.only(bottom: 50)),Text('$moveToPage')
]);
class SliderBox extends StatelessWidget {
final image;
const SliderBox({Key key, this.image}) : super(key: key);
#override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
padding: EdgeInsets.all(10),
child: Image.asset(
image,
height: 300,
fit: BoxFit.fill,
));
}
}
I've modified your widget a little in order to provide you a complete example. You can do this in multiple ways, with AnimationController by itself or even combined with a custom Animation or, you can go the fastest way for what it seems that you want to achieve: using a recursive method that waits a x duration (time stand on a single page) and then animates with some new duration to the new page. For that you can for example:
Make your List available within the state itself in order to retrieve its length.
Create the recursive method that will handle the animation itself.
Make sure that you call it after the first frame is rendered on the screen to prevent the PageController of being accessed before having a PageView rendered on the screen, which you probably don't want. For that you take advantage of the WidgetsBinding.instance.addPostFrameCallback.
class Carousel extends StatefulWidget {
_CarouselState createState() => _CarouselState();
}
class _CarouselState extends State<Carousel> with SingleTickerProviderStateMixin {
final PageController _controller = PageController();
List<Widget> _list = [
SliderBox(
child: FlutterLogo(
colors: Colors.red,
)),
SliderBox(
child: FlutterLogo(
colors: Colors.green,
)),
SliderBox(
child: FlutterLogo(
colors: Colors.blue,
))
];
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _animateSlider());
}
void _animateSlider() {
Future.delayed(Duration(seconds: 2)).then((_) {
int nextPage = _controller.page.round() + 1;
if (nextPage == _list.length) {
nextPage = 0;
}
_controller
.animateToPage(nextPage, duration: Duration(seconds: 1), curve: Curves.linear)
.then((_) => _animateSlider());
});
}
#override
Widget build(BuildContext context) {
PageIndicatorContainer container = new PageIndicatorContainer(
pageView: new PageView(
children: _list,
controller: _controller,
),
length: _list.length,
padding: EdgeInsets.fromLTRB(10, 40, 10, 10),
indicatorSpace: 10,
indicatorColor: Colors.grey[350],
indicatorSelectorColor: Colors.grey,
);
return Stack(
children: <Widget>[
Container(color: Colors.grey[100], height: double.infinity),
Container(color: Colors.white, child: container, margin: EdgeInsets.only(bottom: 50)),
],
);
}
}
class SliderBox extends StatelessWidget {
final Widget child;
const SliderBox({Key key, this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(padding: EdgeInsets.all(10), child: child);
}
}

Flutter: SliverPersistentHeader rebuilds itself on scroll

I have built a small test example for this issue I'm experiencing. You can see from the gif below that the Flutter app only has a header at the top. When I pull down to refresh, the header does not rebuild itself. However, when I push the header upwards, the header rebuilds itself numerous times. Also note that I have not called setState() anywhere in my code so I'm not sure how it knows it needs to rebuild itself when I push the scrollview upwards.
I would like to header to not rebuild itself at all as there is no reason it should rebuild itself. It is static / stateless and should not change at all. The size of the header should also not change (hence the expandedHeight and collapsedHeight are the same at 136.0).
Here is the example code I used for you to recreate this:
import 'package:meta/meta.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:math' as math;
import 'dart:async';
class _TestHeader extends SliverPersistentHeaderDelegate {
_TestHeader({
#required this.collapsedHeight,
#required this.expandedHeight,
#required this.showHeading,
});
bool showHeading;
final double expandedHeight;
final double collapsedHeight;
#override
double get minExtent => collapsedHeight;
#override
double get maxExtent => math.max(expandedHeight, minExtent);
#override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
print("rebuilding headings");
return new SafeArea(
child: Column(children: <Widget>[
const SizedBox(height: 24.0),
new GestureDetector(
onTap: () {
},
child: new Container(
decoration: const BoxDecoration(
color: CupertinoColors.white,
border: const Border(
top: const BorderSide(color: const Color(0xFFBCBBC1), width: 0.0),
bottom:
const BorderSide(color: const Color(0xFFBCBBC1), width: 0.0),
),
),
height: 44.0,
child: new Padding(
padding:
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: new SafeArea(
top: false,
bottom: false,
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
const Text(
'This is my heading',
style: const TextStyle(color: CupertinoColors.activeBlue, fontSize: 16.0),
)
],
),
),
),
),
),
]));
}
#override
bool shouldRebuild(#checked _TestHeader oldDelegate) {
// return false;
return expandedHeight != oldDelegate.expandedHeight ||
collapsedHeight != oldDelegate.collapsedHeight;
}
}
class TestHeaderPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return new TestHeaderState();
}
}
class TestHeaderState extends State<TestHeaderPage> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new CupertinoPageScaffold(
//i will need to convert this to a sliver list to make this work properly.
backgroundColor: const Color(0xFFEFEFF4),
navigationBar: new CupertinoNavigationBar(
middle: new Text('Test Headers'),
),
child: new SafeArea(
child: new CustomScrollView(slivers: <Widget>[
new CupertinoRefreshControl(onRefresh: () {
print("pulling on refresh");
return Future<void>(() {});
}),
new SliverPersistentHeader(
delegate: new _TestHeader(
collapsedHeight: 136.0,
expandedHeight: 136.0,
showHeading: true)),
]),
));
}
}
This is totally normal.
Your _TestHeader is not a widget. Just because it has the build method doesn't mean it's one. :)
You extended SliverPersistentHeaderDelegate, which is used to build SliverPersistentHeader.
The thing is : SliverPersistentHeader is not a widget either. It's a sliver, which is a different way to render things on screen.
And, in the case of SliverPersistentHeader, it is a specific kind of sliver that is rebuilt whenever the scroll offset change. That is, to potentially handle scroll specific animations.
Such as scroll up make the header disappear. And scroll down to make it snap back.