Good day to all. I wanted to use the touchable tool, which allows you to read clicks on the canvas, but there was an error with gesture_detector, which I don't understand how to fix. Here is the code I wrote:
Container(
child: FittedBox(
child: tooth.length == 20 && mouth != null
? SizedBox(
width: mouth?.width.toDouble(),
height: mouth?.height.toDouble(),
child: CanvasTouchDetector(
builder: (context) => CustomPaint(
painter:
FaceOutlinePainter(context),
),
))
: Text('data')),
),
And Flutter sends me to this error. As I understand it, it does not depend on CustomPaint.
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Incorrect GestureDetector arguments.'),
ErrorDescription(
'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.',
),
ErrorHint('Just use the scale gesture recognizer.'),
]);
I will be very grateful for your help.
With best wishes,
from Dmitry
That's because you are using one Listener per CustomPainter, you should use just one Listener for all your Stack.
And if you want to know if the current touch event is inside each Circle , you could use GlobalKeys to get the RenderBox for each Circle, then you have the renderBox, and the PointerEvent, you can easily check the HitTest, check the code:
class _MyHomePageState extends State<MyHomePage> {
GlobalKey _keyYellow = GlobalKey();
GlobalKey _keyRed = GlobalKey();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text("title"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Listener(
onPointerMove: (PointerEvent details) {
final RenderBox box = _keyRed.currentContext.findRenderObject();
final RenderBox boxYellow =
_keyYellow.currentContext.findRenderObject();
final result = BoxHitTestResult();
Offset localRed = box.globalToLocal(details.position);
Offset localYellow = boxYellow.globalToLocal(details.position);
if (box.hitTest(result, position: localRed)) {
print("HIT...RED ");
} else if (boxYellow.hitTest(result, position: localYellow)) {
print("HIT...YELLOW ");
}
},
child: Stack(
children: <Widget>[
CustomPaint(
key: _keyYellow,
painter: ShapesPainter(),
child: Container(
height: 400,
width: 400,
),
),
CustomPaint(
key: _keyRed,
painter: ShapesPainter1(),
child: Container(
height: 200,
width: 200,
),
),
],
),
),
],
),
),
);
}
}
Related
So for this application (Windows, Web) I have 2 requirements:
User can drag around widgets on the screen (drag and drop) to any location.
The app must scale to screen/window size
For (1) I used this answer.
For (2) I used this solution.
As mentioned in the code comment below I can't have both:
If I set logicWidth and logicHeight dynamically depending on the window size, the dragging works fine but the draggable widgets won't scale but instead stay the same size regardless of the window size.
If I set logicWidth and logicHeight to a constant value (the value of the current cleanHeight ) the dragging will be messed up for other screen sizes but then the draggable widgets will scale correctly with the window size.
In other words: for the dragging to work nicely these values need to be matching the window size at any time. But by changing these values I ruin the scaling I need.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';
//containing widgets to drag around
const List<Widget> draggableWidgets = [
DraggableWidget(
draggableWidget: CircleAvatar(
backgroundColor: Colors.green,
radius: 32,
)),
DraggableWidget(
draggableWidget: CircleAvatar(
backgroundColor: Colors.red,
radius: 24,
)),
];
class FrontPageWidget extends ConsumerWidget {
const FrontPageWidget({Key? key}) : super(key: key);
static const routeName = '/frontPage';
#override
Widget build(BuildContext context, WidgetRef ref) {
//screen height and padding
final height = MediaQuery.of(context).size.height;
final padding = MediaQuery.of(context).viewPadding;
// Height (without status and toolbar)
final cleanHeight = height - padding.top - kToolbarHeight;
//either make those values dynamic (cleanHeight updates depending on screen size / window size) OR constant (961px is the cleanHeight on full screen)
//if values are dynamic => the draggable widgets not scaling to screen size BUT dragging works fine
//if values are constant => the draggable widgets do scale to screen size BUT dragging is messed
final logicWidth = cleanHeight; //961
final logicHeight = cleanHeight; //961
return Scaffold(
appBar: AppBar(
title: const Text('Main Page'),
),
body: SizedBox.expand(
child: FittedBox(
fit: BoxFit.contain,
alignment: Alignment.center,
child: Container(
color: Colors.grey,
width: logicWidth,
height: logicHeight,
child: Stack(
children: draggableWidgets,
),
))),
);
}
}
class DraggableWidget extends StatelessWidget {
final Widget draggableWidget;
const DraggableWidget({Key? key, required this.draggableWidget})
: super(key: key);
#override
Widget build(BuildContext context) {
final ValueNotifier<Matrix4> notifier = ValueNotifier(Matrix4.identity());
return Center(
child: MatrixGestureDetector(
onMatrixUpdate: (m, tm, sm, rm) {
notifier.value = m;
},
child: AnimatedBuilder(
animation: notifier,
builder: (ctx, child) {
return Transform(
transform: notifier.value,
child: Center(
child: Stack(
children: [draggableWidget],
),
),
);
},
),
),
);
}
}
One way of doing it is wrapping the draggableWidget in a Transform widget and set the scale factor in relation to the dimensions:
child: AnimatedBuilder(
animation: notifier,
builder: (ctx, child) {
final height = MediaQuery.of(context).size.height;
return Transform(
transform: notifier.value,
child: Center(
child: Stack(
children: [
Transform.scale(
scale: height / 1000,
child: draggableWidget)
],
),
),
);
},
),
I had a similar issue, instead of getting the height from the MediaQuery get it from the LayoutBuilder, I noticed it is working much better when resizing the window.
body: LayoutBuilder(
builder: (context, constraints) {
return SizedBox.expand(
child: FittedBox(
fit: BoxFit.contain,
alignment: Alignment.center,
child: Container(
color: Colors.grey,
width: constraints.maxWidth,
height: constraints.maxHeight,
child: Stack(
children: draggableWidgets,
),
)
)
);
}
);
Another way of achieving this:
To drag around widgets on the screen (drag and drop) to any location.
Draggable Widget
Check Flutter Draggable class
And to scale screen/window size.
Relative Scale
FlutterScreenUtil
I have a vertical scrollView then a horizontal pageView containing images wrapped inside InteractiveViewer.
but it's quite a mess when I try zooming-in with the InteractiveViewer. all those scrollviews are competing for the gestures and I was wonding an easier way to get that fixed.
Edit: So the problem seem to be with onScale gesture(GestureDetector()) or 2 pointer gestures
I have something like
CustomScrollView(
slivers: [
const SliverToBoxAdapter(
child: Container(
width: double.infinity,
height: 400,
child: PageView(
...
InteractiveViewer()
...
)
)
),
]
)
you can disable physic from relevant widget when user start to use interactive, maybe add some condition based on scale, finger, etc.
ScrollPhysics _pagePhysics = const PageScrollPhysics();
ScrollPhysics _customScrollViewPhysics = const ScrollPhysics();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CustomScrollView(
// assign physic for scroll ------------------------
physics: _customScrollViewPhysics,
slivers: [
SliverToBoxAdapter(
child: SizedBox(
height: 400,
child: PageView(
// assign physic for page view --------------------
physics: _pagePhysics,
children: [
Container(
color: Colors.blue,
),
InteractiveViewer(
onInteractionStart: (details) {
/// you can add some condition like this
//if use 2 finger
//if(details.pointerCount == 2){}
// then disable physic
setState(() {
_pagePhysics = const NeverScrollableScrollPhysics();
_customScrollViewPhysics =
const NeverScrollableScrollPhysics();
});
},
onInteractionUpdate: (details) {
//condition based on scale
if (details.scale == 1.2) {}
},
onInteractionEnd: (details) {
// after interaction revert it
setState(() {
_pagePhysics = const PageScrollPhysics();
_customScrollViewPhysics = const ScrollPhysics();
});
},
child: Container(
color: Colors.yellow,
child: const Text("Lorem Ipsum"),
),
)
],
),
),
)
],
),
),
);
}
and if interactiveviewer leave no space for pageview or customScroll its always nice to add some button so you user dont stuck on InteractiveViewer.
you should make your ui like this :
I have a Stack with multiple MatrixGesture Containers with images that can be drag around, pinch zoom and rotate. I want to save the state of each container in the position and shape that it is, because after a little change using setState, everything go back to the original position.
All the information of the images is in a List with a specific object type.
Here is a snippet of the code to display the images:
class NewOutfitState extends State<NewOutfit> {
List<DisplayGarment> garmentsList;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("New"),
body: new Container(
child:MyList(myList: garmentsList, canvasSize: realCanvas,);
)
}
}
class MyListState extends State<MyList>{
List<DisplayGarment> myList;
double realCanvas;
bool flag=false;
int touch=0;
#override
void initState() {
super.initState();
myList=widget.myList;
realCanvas = widget.canvasSize;
}
#override
Widget build(BuildContext context) {
return Stack(
children: getList(),
);
}
List<Widget> getList(){
List<Widget> listWidget=[];
for(int i=0;i<myList.length;i++) {
final ValueNotifier<Matrix4> notifier1= ValueNotifier(Matrix4.identity());
DisplayGarment _garments = myList[i];
listWidget.add(
MatrixGestureDetector(
key: Key(i.toString()),
onMatrixUpdate: (m, tm, sm, rm) {
notifier1.value = m;
},
child: AnimatedBuilder(
animation: notifier1,
builder: (ctx, child) {
return Transform(
transform: notifier1.value,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.all(4),
alignment: Alignment(0, -0.5),
child:
Container(
padding: EdgeInsets.all(0),
height: imgHeigh,
width: imgWidth,
child:
DottedBorder(
color: Colors.transparent,
strokeWidth: 0,
child: Center(
child: CachedNetworkImage(
imageUrl:
'https://fashiers.com/garments_img/'+imgUrl,
height: imgHeigh,
width: imgWidth,
)),
);
,)
)
],),);},),
)
);
}
return listWidget;
}
}
Also is it possible to set a border around the image when that is tap on and remove border on other that was probably tap before?
I appreciate any help with this.
For the first part, you should not put notifier1 initialization inside the build function. That's why every time you use setStatus, your position reset. This part should be initialize inside initState() and that means you should keep all garments location value in this class. (e.g. List<ValueNotifier>)
Second part, indexing the garments may be the instinctive solution. Display/Hide border by:
child: _selectedIndex == i ?
// Widget with border
: //Widget without border
and set _selectedIndex inside onMatrixUpdate()
I'm using Transforms in Flutter to create a scrolling carousel for selecting from various options.
This uses standard elements such as ListView.builder, which all works fine, aside from the fact that the parent widget of the Transform doesn't scale down to fit the content as seen here:
Here's the code used to generate the 'card' (there was actually a Card in there, but I've stripped it out in an attempt to get everything to scale correctly):
return Align(
child: Transform(
alignment: Alignment.center,
transform: mat,
child: Container(
height: 220,
color: color,
width: MediaQuery.of(context).size.width * 0.7,
child: Text(
offset.toString(),
style: TextStyle(color: Colors.white, fontSize: 12.0),
),
),
),
);
}
Even if I remove the 'height' parameter of the Container (so everything scales to fit the 'Text' widget), the boxes containing the Transform widgets still have the gaps around them.
Flutter doesn't seem to have any documentation to show how to re-scale the parent if the object within is transformed - anyone here knows or has any idea of a workaround?
EDIT: The widget returned from this is used within a build widget in a Stateful widget. The stack is Column > Container > ListView.builder.
If I remove the Transform, the Containers fit together as I'd like - it seems that performing a perspective transform on the Container 'shrinks' it's content (in this case, the color - check the linked screen grab), but doesn't re-scale the Container itself, which is what I'm trying to achieve.
I have a tricky solution for this: addPostFrameCallback + overlay.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
// ignore: must_be_immutable
class ChildSizeWidget extends HookWidget {
final Widget Function(BuildContext context, Widget child, Size size) builder;
final Widget child;
final GlobalKey _key = GlobalKey();
OverlayEntry _overlay;
ChildSizeWidget({ this.child, this.builder });
#override
Widget build(BuildContext context) {
final size = useState<Size>(null);
useEffect(() {
WidgetsBinding.instance.addPostFrameCallback((timestamp) {
_overlay = OverlayEntry(
builder: (context) => Opacity(
child: SingleChildScrollView(
child: Container(
child: child,
key: _key,
),
),
opacity: 0.0,
),
);
Overlay.of(context).insert(_overlay);
WidgetsBinding.instance.addPostFrameCallback((timestamp) {
size.value = _key.currentContext.size;
_overlay.remove();
});
});
return () => null;
}, [child]);
if (size == null || size.value == null) {
return child;
} else {
return builder(context, child, size.value);
}
}
}
Usage:
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class HomeView extends HookWidget {
#override
Widget build(BuildContext context) {
final change = useState<bool>(false);
final normal = Container(
color: Colors.blueAccent,
height: 200.0,
width: 200.0,
);
final big = Container(
color: Colors.redAccent,
height: 300.0,
width: 200.0,
);
return Column(
children: [
Container(
alignment: Alignment.center,
child: ChildSizeWidget(
child: change.value ? big : normal,
builder: (context, child, size) => AnimatedContainer(
alignment: Alignment.center,
child: SingleChildScrollView(child: child),
duration: Duration(milliseconds: 250),
height: size.height,
),
),
color: Colors.grey,
),
FlatButton(
child: Text('Toggle child'),
onPressed: () => change.value = !change.value,
color: Colors.green,
),
],
);
}
}
I have a menu with several options, they have different height and with the help of the animations this is ok, it's working really nice for me.
Why are you using Align, as much as I can see in your code, there is no property set or used, to align anything. So try removing Align widget around Transform.
Because according to the documentation, Transform is such a widget that tries to be the same size as their children. So that would satisfy your requirement.
For more info check out this documentation: https://flutter.dev/docs/development/ui/layout/box-constraints
I hope it helps!
The code below lays out a chart in which I'd need to achieve for the chart to be expanded in both vertical (height) and horizontal (width) direction. The suggested method (e.g. https://docs.flutter.io/flutter/widgets/Row-class.html) is to use Expanded in Row or Column.
The chart widget I am trying to expand extends CustomPaint, with no children, everything is painted using a CustomPainter on canvas, in the CustomPainter.paint(canvas, size).
This code
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'vvvvvvvv:',
),
new RaisedButton(
color: Colors.green,
onPressed: _chartStateChanger,
),
new Text(
'vvvvvvvv:',
),
new Expanded( // Expanded in Column, no expansion vertically
child: new Row(
children: [
new Text('>>>'),
new Expanded(// Expanded in Row, expands horizontally
child: new Chart( // extends CustomPaint
// size: chartLogicalSize,
painter: new ChartPainter( // extends CustomPainter
chartData: _chartData,
chartOptions: _chartOptions,
),
),
),
new Text('<<<'),
],
), // row
),
new Text('^^^^^^:'),
new RaisedButton(
color: Colors.green,
onPressed: _chartStateChanger,
),
],
),
),
);
result looks like this: (code of ChartPainter is not shown for brevity)
Inside the ChartPainter.paint(canvas, size) there is a print() printing the size.
print(" ### Size: paint(): passed size = ${size}");
The result from the paint->print above is:
I/flutter ( 4187): ### Size: paint(): passed size = Size(340.0, 0.0)
The print along with the image shows, that the width expansion on the row level was passed to the CustomPainter.print(canvas, size) (width = 340.0), but the height expansion on the column did not get passed to the custom painter print (height = 0.0). Although the result shows that the row did get it's expanded height, if was not passed inside the row to the CustomPainter - 0 height was received.
What do I need to change to achieve the height expansion as well?
Thanks
Here is a reduced test case for the issue you are seeing. The solution is to give your Row a crossAxisAlignment of CrossAxisAlignment.stretch. Otherwise it will try to determine the intrinsic height of your CustomPaint which is zero because it doesn't have a child.
import 'package:flutter/material.dart';
// from https://stackoverflow.com/questions/45875334/how-to-achieve-expansion-of-a-widget-in-both-vertical-height-and-horizontal-w
class MyCustomPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) {
// NOT using crossAxisAlignment: CrossAxisAlignment.stretch => width = 222.0, height=0.0
// using crossAxisAlignment: CrossAxisAlignment.stretch => width = 222.0, height=560.0
print("width = ${size.width}, height=${size.height}");
canvas.drawRect(Offset.zero & size, new Paint()..color = Colors.blue);
}
#override
bool shouldRepaint(MyCustomPainter other) => false;
}
void main() {
runApp(new MaterialApp(
home: new Scaffold(
body: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('Above Paint'),
// Expanded - because we are in Column, expand the
// contained row's height
new Expanded(
child: new Row(
// The crossAxisAlignment is needed to give content height > 0
// - we are in a Row, so crossAxis is Column, so this enforces
// to "stretch height".
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Text('Left of Paint'),
// Expanded - because we are in Row, expand the
// contained Painter's width
new Expanded(
child: new CustomPaint(
painter: new MyCustomPainter(),
),
),
new Text('Right of Paint'),
],
),
),
new Text('Below Paint'),
],
)
),
));
}
There is a better way than nesting Row, Expanded and Column widget. You can use the Container widget with Constraints to BoxConstraints.expand().
Example Code:
Widget build(BuildContext context) {
return Container(
constraints: BoxConstraints.expand(),
child: FutureBuilder(
future: loadImage(),
builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.waiting :
return Center(child: Text("loading..."),);
default:
if (snapshot.hasError) {
return Center(child: Text("error: ${snapshot.error}"),);
} else {
return ImagePainter(image: snapshot.data);
}
}
},
),
);
}
Use SizedBox.expand:
SizedBox.expand(
child: YourWidget() // Could be anything like `Column`, `Stack`...
)
For those who struggled to get gradient together with Material behaviour:
return new Stack(
children: <Widget>[
new Material(
elevation: 10,
borderRadius: new BorderRadius.all(new Radius.circular(30.0)),
color: Colors.transparent,
child: new Container(
constraints: BoxConstraints.expand(height: 50),
),
),
new Container(
constraints: BoxConstraints.expand(height: 50),
decoration: BoxDecoration(
borderRadius: new BorderRadius.all(new Radius.circular(30.0)),
gradient: new LinearGradient(
colors: [color1, color2],
begin: Alignment.topCenter,
end: Alignment.bottomCenter),
),
child: new FloatingActionButton.extended(
backgroundColor: Colors.transparent,
foregroundColor: Colors.transparent,
highlightElevation: 0,
elevation: 0,
onPressed: () {
onPressed();
},
label: new Text(this.caption,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.body1),
),
)
],
)