Flutter Scroll with fixed start end end point - flutter

I want to create a scroll that scrolls from one fixed point to another. With Positioned I can draw an Image to an absolute position and I want a scroll that works in a similar way. A bidirectional scroll that has coordinates where it should stop scrolling and isn't sized by the Widges inside it.
As an example it should be able to scroll to the top of the first image that has an absolute position.
It is supposed to be a bidirectional infinity scroll, without memory leaks. I want to remove and add images above without messing up the scrollprogress. That’s why I chose absolute positions for the images and want to know how to make it scrollable.
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Stack(children: <Widget>[
Container(
height: 1500,
width: double.maxFinite,
color: Colors.blue,
),
Positioned(
top: -100,
width: 500,
height: 600,
left: 0,
child: Image.network("https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg")),
Positioned(
top: 400,
width: 500,
height: 500,
left: 0,
child: Image.network("https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg")),
Positioned(
top: 900,
width: 500,
height: 500,
left: 0,
child: Image.network("https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg"))
]),
));

You can use LazyLoading package or infiniteScrollPagination. if you face some issue when parsing the list, check out this post tempListModel

Perhaps, you want to achieve a vertical (or maybe horizontal) carousel slider for images. If I'm not wrong, I recommend a package that can easily manage your code and save time.
Package link: https://pub.dev/packages/carousel_slider

Just import the carousel slider package from the below-mentioned site.
Link: https://pub.dev/packages/carousel_slider
Then, try this example code I wrote for you. Kindly explore the carousel options property. This package is popular as well as feature-rich.
My code:
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
const Demo({Key? key}) : super(key: key);
#override
State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
final CarouselController _carouselController = CarouselController();
final List<String> _imageURLsList = [
"https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg",
"https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg",
"https://trade.recosurfaces.com/wp-content/uploads/2020/08/100X-PGB1-DBWT-800x800.jpg",
];
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Expanded(
child: CarouselSlider.builder(
itemCount: _imageURLsList.length,
carouselController: _carouselController,
options: CarouselOptions(
scrollDirection: Axis.vertical,
enableInfiniteScroll: true,
),
itemBuilder: (context, index, realIndex) {
return Image.network(_imageURLsList[index]);
},
),
),
],
),
),
);
}
}

Related

Flutter - Draggable AND Scaling Widgets

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

ListView widget not entirely visible when scaled

When I scale a horizontal ListView widget, I observe that only a portion of the list items are visible when the widget is scrolled all the way to the right:
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final sideLength = 50.0;
final scale = 2.0;
return MaterialApp(
scrollBehavior: MyCustomScrollBehavior(),
home: Scaffold(
body: Transform.scale(
scale: scale,
alignment: Alignment(-1, -1),
child: Container(
height: sideLength * scale,
child: ListView.builder(
itemCount: 20,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Container(
width: sideLength,
height: sideLength,
child: Text(index.toString()),
decoration: BoxDecoration(
border: Border.all(width: 3, color: Colors.red))),
)),
)));
}
}
class MyCustomScrollBehavior extends MaterialScrollBehavior {
// Override behavior methods and getters like dragDevices
#override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
};
}
On the Pixel 2 emulator, only the first 16 items are visible when I scroll to extreme right. For example:
When the scale is 1 or if the Transform.scale widget is not there, all 20 items are visible.
I observe the following behavior:
Total item count
Last item scrollable to
8
4
10
6
20
16
30
26
50
46
So it seems like the last 4 items are always left out.
Ultimately my goal is to create a responsive widget that scales according to the dimensions of screen, so I'm looking for a generic solution.
The custom scroll behavior is only there so that horizontal scrolling works on dartpad.dev, as per this answer.
Transform only affects how the child should be painted.
On the other hand, The scale argument multiplies the x and y axes.
For example: Imagine a photographer who is taking a landscape photo that contains a tree, now if the photographer gets closer to the tree, the upper part of the tree will slightly be out of the photo.
Try adding padding or margin to the Container and observe how the widget is affected by the scale.
Then you will know how to manipulate it.
body: Transform.scale(
scale: scale,
alignment: Alignment(0, -5),
child: Container(
height: sideLength * scale,
margin: EdgeInsets.only(left: 100, right: 100),
child: ListView.builder(
Give here width and height by MediaQuery
Widget build(BuildContext context) {
return MaterialApp(
scrollBehavior: MyCustomScrollBehavior(),
home: Scaffold(
body: Transform.scale(
scale: scale,
alignment: Alignment(-1, -1),
child: Container(
height: sideLength * scale,
child: ListView.builder(
itemCount: 20,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Container(
width: MediaQuery.of(context).size.width*0.90 ,
height: MediaQuery.of(context).size.height*0.80 ,
child: Text(index.toString()),
decoration: BoxDecoration(
border: Border.all(width: 3, color: Colors.red))),
)),
)));
}
I worked around this issue by:
setting itemCount to a higher value than the desired item count. This allows you to scroll to the last desired item in the ListView
having a scroll controller that checks whether you're past the last visible desired item within the viewport. If so, jump to the last possible scroll offset within the viewport
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final ScrollController _scrollController = ScrollController();
static const actualTotalItems = 20;
static const sideLength = 50.0;
static const scale = 2.0;
MyApp() {
_scrollController.addListener(() {
if (_scrollController.offset > sideLength * actualTotalItems - _scrollController.position.viewportDimension / scale) {
_scrollController.jumpTo(sideLength * actualTotalItems - _scrollController.position.viewportDimension / scale);
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
scrollBehavior: MyCustomScrollBehavior(),
home: Scaffold(
body: Container(
transform: Matrix4.diagonal3Values(scale, scale, 1),
height: sideLength * scale,
child: ListView.builder(
itemCount: actualTotalItems * 2,
scrollDirection: Axis.horizontal,
controller: _scrollController,
itemBuilder: (context, index) => Container(
width: sideLength,
height: sideLength,
child: Text(index.toString()),
decoration: BoxDecoration(border: Border.all(width: 3, color: Colors.red)))))));
}
}
class MyCustomScrollBehavior extends MaterialScrollBehavior {
// Override behavior methods and getters like dragDevices
#override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
};
}
I scaled the widget using the transform property in the Container to have a smaller widget tree, but that has no impact on the solution. The Transform widget could have been used as in the OP.

Why is draggable widget not being placed in correct position?

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.

Resizing parent widget to fit child post 'Transform' in Flutter

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!

RenderListWheelViewport object was given an infinite size during layout

I am using ListWheelScrollView Widget to give a wheeling effect to my list item but getting the error as mentioned. I just want to show Stacked Items with some image and texts in individual list item and give a 3D Wheeling effect to them.
Below is my code ->
class ExploreWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _ExploreState();
}
class _ExploreState extends State<ExploreWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: Column(
children: <Widget>[
_header(),
_exploreList()
],
)
);
}
Widget _header(){
return SizedBox(
height: 200,
width: 800,
);
}
Widget _exploreList(){
return ListWheelScrollView.useDelegate(
itemExtent: 75,
childDelegate: ListWheelChildBuilderDelegate(
builder:(context,index){
return Container(
height: 500,
width: 800,
child: Stack(
children: <Widget>[
Image(image: AssetImage(
_products[index].image
)),
Text(_products[index].name,style: Style.sectionTitleWhite,),
Text('70% off',style: Style.cardListTitleWhite,),
],
),
);
}
),
);
}
}
The error was occuring due to the way _exploreList() widget is implemented. This widget is wrapped inside Column which doesn't scroll in itself. Moreover, you are returning a ScrollView that has an infinite size. Hence it was throwing the said error. To resolve this issue, wrap _exploreList() widget inside Flexible which takes only minimum available space to render and scroll. Working sample code below:
body: Column(
children: <Widget>[
_header(),
Flexible(
child: _exploreList()
)
],
)
Now you should be able to use WheelScrollView properly.