I am learning flutter for some time. But I do not seem to understand fully what is FractionalTranslation class despite docs and some examples.
Documentation says: FractionalTranslation class applies a translation transformation before painting its child.
But what does it mean? Could you explain it to me in more detail?
FractionalTranslation class is essentially a type of Transform, and it is also used to do The difference of translation transformation is that its translation unit is a multiple of the width and height of the control. It is defined as follows
FractionalTranslation({
Key key,
#required Offset translation,
bool transformHitTests: true,
Widget child })
It can be seen that its definition is the Transform.translatesame. The difference is translation the understanding of parameters. Let’s use a few examples to explain the use of FractionalTranslation
FractionalTranslation use
The translation distance of the Text control to the right is 0.5 times the width of the Text control
Container(
color: Colors.amberAccent,
alignment: Alignment.center,
child: FractionalTranslation(
translation: Offset(0.5, 0),
child: Text("Hello world")),
),
The distance to translate the Text control to the right is 2 times the width of the Text control
Container(
color: Colors.amberAccent,
alignment: Alignment.center,
child: FractionalTranslation(
translation: Offset(2, 0),
child: Text("Hello world")),
),
Move the Text control to the right and down. The right translation distance is 1 times the Text width, and the downward translation distance is 1.5 times the Text height.
Container(
color: Colors.amberAccent,
alignment: Alignment.center,
child: FractionalTranslation(
translation: Offset(1, 1.5),
child: Text("Hello world")),
),
Complete example
import 'package:flutter/material.dart';
import 'dart:math' as math;
class TransformDemo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primaryColor: Colors.blue),
home: HomeWidget(),
);
}
}
class HomeWidget extends StatefulWidget {
#override
State createState() {
return HomeState();
}
}
class HomeState extends State<HomeWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("TransformDemo"),),
body: Container(
color: Colors.amberAccent,
alignment: Alignment.center,
child: FractionalTranslation(
translation: Offset(1, 0),
child: Text("Hello world")),
),
);
}
}
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
My Flutter application makes use of the relatively new Windows build tools and the community fluent_ui package.
In an attempt to make my application look more native, I have opted to remove the default Windows title bar using the window_manager package and implement my own. However, this introduces the issue of not being able to move the window by dragging the top of it.
Is there a way to make a widget a window drag point to allow for this?
I recently found a solution by making DraggableAppBar. I'm also using window_manager package to add window control buttons to appbar.
Solution: use DraggableAppBar instead of AppBar in scaffold.
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
import 'package:window_manager/window_manager.dart';
class DraggebleAppBar extends StatelessWidget implements PreferredSizeWidget {
final String title;
final Brightness brightness;
final Color backgroundColor;
const DraggebleAppBar({
super.key,
required this.title,
required this.brightness,
required this.backgroundColor,
});
#override
Widget build(BuildContext context) {
return Stack(
children: [
getAppBarTitle(title),
Align(
alignment: AlignmentDirectional.centerEnd,
child: SizedBox(
height: kToolbarHeight,
width: 200,
child: WindowCaption(
backgroundColor: backgroundColor,
brightness: brightness,
),
),
)
],
);
}
Widget getAppBarTitle(String title) {
if (UniversalPlatform.isWeb) {
return Align(
alignment: AlignmentDirectional.center,
child: Text(title),
);
} else {
return DragToMoveArea(
child: SizedBox(
height: kToolbarHeight,
child: Align(
alignment: AlignmentDirectional.center,
child: Text(title),
),
),
);
}
}
#override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
I'm struggling to understand why after moving a draggable widget it gets placed into another position about 100px lower than where I'm placing it... The only thing I can think of is that it's adding the height of the Appbar and status bar ...
I thought I was doing something wrong so I decided to create the simplest example I could and it's still doing the same thing.
Just to confirm, I don't want to use drag targets, or anything like that ... I'd simply like the draggable widget to land exactly where I place the thing. However, I do need it inside of a Stack
[EDIT] It seems that removing the AppBar allows the Draggable to land exactly where you place it. However, I don't want the draggable widget to go behind the Status bar and so after adding a SafeArea I'm left with a similar problem. [/EDIT]
import 'package:flutter/material.dart';
class DraggableTest extends StatefulWidget {
static const routeName = '/draggable-test';
#override
_DraggableTestState createState() => _DraggableTestState();
}
class _DraggableTestState extends State<DraggableTest> {
Offset _dragOffset = Offset(0, 0);
Widget _dragWidget() {
return Positioned(
left: _dragOffset.dx,
top: _dragOffset.dy,
child: Draggable(
child: Container(
height: 120,
width: 90,
color: Colors.black,
),
childWhenDragging: Container(
height: 120,
width: 90,
color: Colors.grey,
),
feedback: Container(
height: 120,
width: 90,
color: Colors.red,
),
onDragEnd: (drag) {
setState(() {
_dragOffset = drag.offset;
});
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Stack(
children: <Widget>[
_dragWidget(),
],
),
);
}
}
The main issue has to do with global position vs local position: Your Draggable widget gives global position whereas the Positioned inside your Stack takes local position. When there is no AppBar global and local positions match so the issue disappear but is still here.
So the real fix here is:
Convert your global coordinates to locale ones:
RenderBox renderBox = context.findRenderObject();
onDragEnd(renderBox.globalToLocal(drag.offset));
You now need a context. This context has to be local (the of the Draggable for example). So in the final implementation you can embed either the Stack or the Draggable in a StatelessWidget class in order to get a local context.
Here is my final implementation:
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(
home: DraggableTest(),
));
}
class DraggableTest extends StatefulWidget {
static const routeName = '/draggable-test';
#override
_DraggableTestState createState() => _DraggableTestState();
}
class _DraggableTestState extends State<DraggableTest> {
Offset _dragOffset = Offset(0, 0);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Stack(
children: <Widget>[
Positioned(
left: _dragOffset.dx,
top: _dragOffset.dy,
child: DragWidget(onDragEnd: onDragEnd),
),
],
),
);
}
void onDragEnd(Offset offset) {
setState(() {
_dragOffset += offset;
});
}
}
class DragWidget extends StatelessWidget {
final void Function(Offset) onDragEnd;
const DragWidget({Key key, this.onDragEnd}) : super(key: key);
#override
Widget build(BuildContext context) {
return Draggable(
child: Container(
height: 120,
width: 90,
color: Colors.black,
),
childWhenDragging: Container(
height: 120,
width: 90,
color: Colors.grey,
),
feedback: Container(
height: 120,
width: 90,
color: Colors.red,
),
onDragEnd: (drag) {
RenderBox renderBox = context.findRenderObject();
onDragEnd(renderBox.globalToLocal(drag.offset));
},
);
}
}
Note that the offset returned by renderBox.globalToLocal(drag.offset) is the offset inside the Draggable (from the start position to the end position). It is why we need to compute the final offset by setting _dragOffset += offset.
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!
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: TestCode(),
);
}
}
class TestCode extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 100,
color: Colors.red,
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
);
}
}
In fact, this code is very simple. I just want to display a 200 * 100 red cube and a 100 * 100 green cube.
But the running effect is full screen green? Why is that?
Next, I added a Scaffold toTestCode, as follows
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(body: TestCode()),
);
}
The effect again seems to be closer, showing a 200 * 100 green cuboid? Why is that?
Next, I added an alignment to the first Container, as follows
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.topLeft,
width: 200,
height: 100,
color: Colors.red,
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
);
}
Finally achieved the desired effect, why is this, who can explain, I must figure this out.
This is caused by what we call "tight vs loose constraints" in Flutter.
TD;DR, width/height are tight constraints (in the sense that there's only a single possibility).
But you never specified to the framework how to switch between the tight constraint of 200x200 specified by the parent, to the tight constraint of 100x100 of the child.
This cause a constraint conflict. Both widgets have a single possibility, and there's nothing that allows both to live together (like an alignment).
In that situation, the constraints of the parent always win, and we therefore end up with a 200x200 square where the child fills its parent.
If that is not what you want; then you should transform your "tight" constraint into a "loose" constraint.
A loose constraint is a constraint that offer the child multiple possibilities, which usually remove the conflict.
The most common way to introduce a loose constraint is to use Alignment (or Center or the alignment property of Container).
As such, if you write:
Container(
width: 200,
height: 100,
color: Colors.red,
child: Center(
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
),
);
then in that situation, Center will act as a middle ground between the parent and child Container.
It will understand that both wants a different size. And it will solve the conflict by aligning the child in the parent.
Now, why is this desired you may ask? Why can't Flutter implicitly add an alignment here?
That is because in many situations, this behavior is desired.
Basically, this ensures that there's always a way to customize the size of something (without having to expose tons of properties on all widgets).
Take RaisedButton as an example. It doesn't expose anything to change its size, but we may want it to fill the screen.
In that situation we'd write:
SizedBox.expand(
child: RaisedButton(...),
)
Because of the behavior we explained previously with the parent overriding the child size when there's a conflict, this code will produce a RaisedButton that properly fills the screen.
height and width properties getting overrided. You can have more info about box constraints on this article:
Dealing with box constraints
Flutter has bunch of layout widgets that can get the job done. In your case you gave Container to the home property of MaterialApp. This set the minimum size of the Container to the screen size. MaterialApp wants his child to fill all the screen in order to prevent any black pixels. This is an expected behaviour. However you can use a layout widget that can break this constraint, it may be Center , FittedBox or else.
An example with FittedBox:
class TestCode extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.scaleDown,
child: Container(
width: 200,
height: 100,
color: Colors.red,
child: FittedBox(
fit: BoxFit.scaleDown,
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
),
),
);
}
}
Output:
Always remember that the container by default takes the dimensions of the parent, and it's a good practice to wrap all your elements/widgets in a root top level Container and then wrap each container in the widget tree with widgets that position the desired Container (Center can be such a widget)
An easy work-around solution for your problem would be:
// The root container
Container(
//Center for positioning the child Container properly
child: Center(
child: Container(
height: 100,
width: 200,
color: Colors.red,
//Center for positioning the child Container properly
child: Center(
child: Container(
height: 100,
width: 100,
color: Colors.green,
),
),
),
),
),
Just change your code into this. You have to specify alignment.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: TestCode(),
);
}
}
class TestCode extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: 200.0,
height: 100.0,
color: Colors.red,
alignment: Alignment.center, // where to position the child
child: Container(
width: 100.0,
height: 100.0,
color: Colors.green,
),
);
}
}