Flutter ListView scroll to index insufficient scrolling - flutter

i have a expandable listview and i have a scroll problem. It is not a problem if it is selected individually or by sliding slowly, but when you scroll and select fast it will be insufficient slide problem.
I added a 'dartpad' so that the code can be tested. What can be the problem?
Code: https://dartpad.dev/c4015095fc23456619eb20a5edcb0e8b
Video: https://vimeo.com/532603204

This is an interesting problem, I had some time to deal with this, and it appears the scroll controller is updated well as I see in the log. But, for some reason, it didn't work, so I put scroll view around the list and gave the ListView.builder no scroll. Only this to take account for is the last parts of the list, because you don't want to scroll more down if you are in the last parts because you cant go down more.
This probably isn't the best solution but it is what I managed to put together, hope this helps.
import 'dart:developer';
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: 'Flutter Scroll Bug Demo',
home: MainScreen(),
);
}
}
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
final _demoList = List.generate(100, (index) => 'List Item $index');
int _expandedIndex = -1;
final _scrollController = ScrollController();
bool _isExpanded = false;
bool _isInLastPart = false;
#override
Widget build(BuildContext context) {
_isInLastPart = (_expandedIndex > _demoList.length - 15);
final _size = MediaQuery.of(context).size;
return SafeArea(
child: Scaffold(
body: SingleChildScrollView(
controller: _scrollController,
child: SizedBox(
height: (48 * _demoList.length).toDouble() +
((_isExpanded && _isInLastPart) ? 80 : 0).toDouble(),
width: _size.width,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return GestureDetector(
onTap: () => clickItem(index),
child: Container(
color: Colors.grey,
height: (_expandedIndex == index && _isExpanded) ? 120 : 40,
margin: EdgeInsets.only(bottom: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_demoList[index]),
if (_expandedIndex == index && _isExpanded)
Column(
children: <Widget>[
Text('text'),
Text('text'),
Text('text'),
Text('text'),
Text('text'),
],
),
],
),
),
);
},
itemCount: _demoList.length,
),
),
),
),
);
}
clickItem(int index) {
setState(() {
if (_expandedIndex == index)
_isExpanded = !_isExpanded;
else
_isExpanded = true;
_expandedIndex = index;
});
if (_expandedIndex < _demoList.length - 15) {
// log("expanded index_: $_expandedIndex, index: $index, jump to: ${index * 48.toDouble()}/${99 * 48.toDouble()}, scroll> ${_scrollController.position.pixels},isExpanded: $_isExpanded");
_scrollController.jumpTo(index * 48.toDouble());
} else {
if (_isExpanded) {
// log("expanded index_: $_expandedIndex, index: $index, jump to: ${83 * 48.toDouble() + 8}/${99 * 48.toDouble()}, scroll> ${_scrollController.offset},isExpanded: $_isExpanded");
_scrollController.jumpTo(83 * 48.toDouble() + 80 + 8);
} else {
// log("expanded index_: $_expandedIndex, index: $index, jump to: ${83 * 48.toDouble() + 80 + 8}/${99 * 48.toDouble()}, scroll> ${_scrollController.offset}, isExpanded: $_isExpanded");
_scrollController.jumpTo(83 * 48.toDouble() + 8);
}
}
}
}

Related

how to achieve a functionality like linear loading bar which will load up as user move between various screens

I am using android studio and flutter. I want to build the screen as shown below in the image:screen Image
let's say I have 4 screens. on the first screen, the bar will load up to 25%. the user will move to next screen by clicking on continue, the linearbar will load up to 50% and so on. the user will get back to previous screens by clicking on the back button in the appbar.
I tried stepper but it doesn't serve my purpose.
You can use the widget LinearProgressIndicator(value: 0.25,) for the first screen and with value: 0.5 for the second screen etc.
If you want to change the bar value within a screen, just use StatefullWidget's setState(), or any state management approaches will do.
import 'package:flutter/material.dart';
class ProgressPage extends StatefulWidget {
const ProgressPage({super.key});
#override
State<ProgressPage> createState() => _ProgressPageState();
}
class _ProgressPageState extends State<ProgressPage> {
final _pageController = PageController();
final _pageCount = 3;
int? _currentPage;
double? _screenWidth;
double? _unit;
double? _progress;
#override
void initState() {
super.initState();
_pageController.addListener(() {
_currentPage = _pageController.page?.round();
setState(() {
_progress = (_currentPage! + 1) * _unit!;
});
});
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
_screenWidth = MediaQuery.of(context).size.width;
_unit = _screenWidth! / _pageCount;
_progress ??= _unit;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('HOZEROGOLD')),
body: Column(
children: [
Align(
alignment: Alignment.topLeft,
child: Container(
color: Colors.yellow,
height: 10,
width: _progress,
),
),
Expanded(
child: PageView(
controller: _pageController,
children: _createPage(),
),
),
],
),
);
}
List<Widget> _createPage() {
return List<Widget>.generate(
_pageCount,
(index) => Container(
color: Colors.white,
child: Center(
child: ElevatedButton(
onPressed: () => _moveNextPage(),
child: Text('NEXT $index'),
),
),
),
);
}
void _moveNextPage() {
if (_pageController.page!.round() == _pageCount-1) {
_pageController.jumpToPage(0);
} else {
_pageController.nextPage(
curve: Curves.bounceIn,
duration: const Duration(milliseconds: 100));
}
}
}
HAPPY CODING! I hope it will be of help.

Flip page effect using Flutter and flip_widget library

I am working on a flutter app, and what I am trying to implement is a flip effect using this plugin Flip Widget.
The plugin works fine for the right to left (next page) drag effect but I can't make the same effect work from left to right (previous page), I have tried different values for the tilt and percentage value (negative and positive) and nothing worked so far. Here is the code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flip_widget/flip_widget.dart';
import 'dart:math' as math;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
const double _MinNumber = 0.008;
double _clampMin(double v) {
if (v < _MinNumber && v > -_MinNumber) {
if (v >= 0) {
v = _MinNumber;
} else {
v = -_MinNumber;
}
}
return v;
}
class _MyAppState extends State<MyApp> {
GlobalKey<FlipWidgetState> _flipKey = GlobalKey();
Offset _oldPosition = Offset.zero;
bool _visible = true;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
Size size = Size(256, 256);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
mainAxisSize: MainAxisSize.min,
children: [
Visibility(
child: Container(
width: size.width,
height: size.height,
child: GestureDetector(
child: FlipWidget(
key: _flipKey,
textureSize: size * 2,
child: Container(
color: Colors.blue,
child: Center(
child: Text("hello"),
),
),
),
onHorizontalDragStart: (details) {
_oldPosition = details.globalPosition;
_flipKey.currentState?.startFlip();
},
onHorizontalDragUpdate: (details) {
Offset off = details.globalPosition - _oldPosition;
double tilt = 1/_clampMin((-off.dy + 20) / 100);
double percent = math.max(0, -off.dx / size.width * 1.4);
percent = percent - percent / 2 * (1-1/tilt);
_flipKey.currentState?.flip(percent, tilt);
},
onHorizontalDragEnd: (details) {
_flipKey.currentState?.stopFlip();
},
onHorizontalDragCancel: () {
_flipKey.currentState?.stopFlip();
},
),
),
visible: _visible,
),
TextButton(
onPressed: () {
setState(() {
_visible = !_visible;
});
},
child: Text("Toggle")
)
],
),
),
);
}
}
The library developer responded to this Github issue and provided an excellent example code for this feature.
https://github.com/gsioteam/flip_widget/issues/2
Thanks for the great work #gsioteam

Implementing custom horizontal scroll of listview of items like Louis Vuitton app

Recently I have downloaded the Louis Vuitton App. I found a strange type of horizontal scroll of product items in listview. I tried card_swiper package but couldnot get through it. How can I achieve such scroll as in gif below?
the trick here is to use a stack and:
Use a page view to display every element except the first one
Use a left aligned FractionallySizedBox which displays the first item and grows with the first item offset
It took me a few tries but the result is very satisfying, I'll let you add the bags but here you go with colored boxes ;) :
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: FunList()));
}
class FunList extends StatefulWidget {
#override
State<FunList> createState() => _FunListState();
}
class _FunListState extends State<FunList> {
/// The colors of the items in the list
final _itemsColors = List.generate(
100,
(index) => Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0),
);
/// The current page of the page view
double _page = 0;
/// The index of the leftmost element of the list to be displayed
int get _firstItemIndex => _page.toInt();
/// The offset of the leftmost element of the list to be displayed
double get _firstItemOffset => _controller.hasClients ? 1 - (_page % 1) : 1;
/// Controller to get the current position of the page view
final _controller = PageController(
viewportFraction: 0.25,
);
/// The width of a single item
late final _itemWidth = MediaQuery.of(context).size.width * _controller.viewportFraction;
#override
void initState() {
super.initState();
_controller.addListener(() => setState(() {
_page = _controller.page!;
}));
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Center(
child: Stack(
children: [
Positioned.fill(
child: Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: _itemWidth,
child: FractionallySizedBox(
widthFactor: _firstItemOffset,
heightFactor: _firstItemOffset,
child: PageViewItem(color: _itemsColors[_firstItemIndex]),
),
),
),
),
SizedBox(
height: 200,
child: PageView.builder(
padEnds: false,
controller: _controller,
itemBuilder: (context, index) {
return Opacity(
opacity: index <= _firstItemIndex ? 0 : 1,
child: PageViewItem(color: _itemsColors[index]),
);
},
itemCount: _itemsColors.length,
),
),
],
),
);
}
}
class PageViewItem extends StatelessWidget {
final Color color;
const PageViewItem({
Key? key,
required this.color,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
color: color,
);
}
}

Flutter Web "smooth scrolling" on WheelEvent within a PageView

With the code below
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
#override
Widget build(BuildContext context) => MaterialApp(
home: const MyHomePage(),
);
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) => DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: const Center(
child: Text('use the mouse wheel to scroll')),
bottom: TabBar(
tabs: const [
Center(child: Text('ScrollView')),
Center(child: Text('PageView'))
],
),
),
body: TabBarView(
children: [
SingleChildScrollView(
child: Column(
children: [
for (int i = 0; i < 10; i++)
Container(
height: MediaQuery.of(context).size.height,
child: const Center(
child: FlutterLogo(size: 80),
),
),
],
),
),
PageView(
scrollDirection: Axis.vertical,
children: [
for (int i = 0; i < 10; ++i)
const Center(
child: FlutterLogo(size: 80),
),
],
),
],
),
),
);
}
You can see, running it on dartpad or from this video,
that using the mouse wheel to scroll a PageView provides a mediocre experience (at best),
This is a known issue #35687 #32120, but I'm trying to find a workaround
to achieve either smooth scrolling for the PageView or at least prevent the "stutter".
Can someone help me out or point me in the right direction?
I'm not sure the issue is with PageScrollPhysics;
I have a gut feeling that the problem might be with WheelEvent
since swiping with multitouch scroll works perfectly
The problem arises from chain of events:
user rotate mouse wheel by one notch,
Scrollable receives PointerSignal and calls jumpTo method,
_PagePosition's jumpTo method (derived from ScrollPositionWithSingleContext) updates scroll position and calls goBallistic method,
requested from PageScrollPhysics simulation reverts position back to initial value, since produced by one notch offset is too small to turn the page,
another notch and process repeated from step (1).
One way to fix issue is perform a delay before calling goBallistic method. This can be done in _PagePosition class, however class is private and we have to patch the Flutter SDK:
// <FlutterSDK>/packages/flutter/lib/src/widgets/page_view.dart
// ...
class _PagePosition extends ScrollPositionWithSingleContext implements PageMetrics {
//...
// add this code to fix issue (mostly borrowed from ScrollPositionWithSingleContext):
Timer timer;
#override
void jumpTo(double value) {
goIdle();
if (pixels != value) {
final double oldPixels = pixels;
forcePixels(value);
didStartScroll();
didUpdateScrollPositionBy(pixels - oldPixels);
didEndScroll();
}
if (timer != null) timer.cancel();
timer = Timer(Duration(milliseconds: 200), () {
goBallistic(0.0);
timer = null;
});
}
// ...
}
Another way is to replace jumpTo with animateTo. This can be done without patching Flutter SDK, but looks more complicated because we need to disable default PointerSignalEvent listener:
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class PageViewLab extends StatefulWidget {
#override
_PageViewLabState createState() => _PageViewLabState();
}
class _PageViewLabState extends State<PageViewLab> {
final sink = StreamController<double>();
final pager = PageController();
#override
void initState() {
super.initState();
throttle(sink.stream).listen((offset) {
pager.animateTo(
offset,
duration: Duration(milliseconds: 200),
curve: Curves.ease,
);
});
}
#override
void dispose() {
sink.close();
pager.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mouse Wheel with PageView'),
),
body: Container(
constraints: BoxConstraints.expand(),
child: Listener(
onPointerSignal: _handlePointerSignal,
child: _IgnorePointerSignal(
child: PageView.builder(
controller: pager,
scrollDirection: Axis.vertical,
itemCount: Colors.primaries.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(color: Colors.primaries[index]),
);
},
),
),
),
),
);
}
Stream<double> throttle(Stream<double> src) async* {
double offset = pager.position.pixels;
DateTime dt = DateTime.now();
await for (var delta in src) {
if (DateTime.now().difference(dt) > Duration(milliseconds: 200)) {
offset = pager.position.pixels;
}
dt = DateTime.now();
offset += delta;
yield offset;
}
}
void _handlePointerSignal(PointerSignalEvent e) {
if (e is PointerScrollEvent && e.scrollDelta.dy != 0) {
sink.add(e.scrollDelta.dy);
}
}
}
// workaround https://github.com/flutter/flutter/issues/35723
class _IgnorePointerSignal extends SingleChildRenderObjectWidget {
_IgnorePointerSignal({Key key, Widget child}) : super(key: key, child: child);
#override
RenderObject createRenderObject(_) => _IgnorePointerSignalRenderObject();
}
class _IgnorePointerSignalRenderObject extends RenderProxyBox {
#override
bool hitTest(BoxHitTestResult result, {Offset position}) {
final res = super.hitTest(result, position: position);
result.path.forEach((item) {
final target = item.target;
if (target is RenderPointerListener) {
target.onPointerSignal = null;
}
});
return res;
}
}
Here is demo on CodePen.
Quite similar but easier to setup:
add smooth_scroll_web ^0.0.4 to your pubspec.yaml
...
dependencies:
...
smooth_scroll_web: ^0.0.4
...
Usage:
import 'package:smooth_scroll_web/smooth_scroll_web.dart';
import 'package:flutter/material.dart';
import 'dart:math'; // only for demo
class Page extends StatefulWidget {
#override
PageState createState() => PageState();
}
class PageState extends State<Page> {
final ScrollController _controller = new ScrollController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("SmoothScroll Example"),
),
body: SmoothScrollWeb(
controller: controller,
child: Container(
height: 1000,
child: ListView(
physics: NeverScrollableScrollPhysics(),
controller: _controller,
children: [
// Your content goes here, thoses children are only for demo
for (int i = 0; i < 100; i++)
Container(
height: 60,
color: Color.fromARGB(1,
Random.secure().nextInt(255),
Random.secure().nextInt(255),
Random.secure().nextInt(255)),
),
],
),
),
),
);
}
}
Thanks you hobbister !
Refer to flutter's issue #32120 on Github.
I know that it has been almost 1.5 year from this question, but I found a way that works smoothly. Maybe this will be very helpful whoever read it. Add a listener to your pageview controller with this code (You can make adjustments on duration or nextPage/animateToPage/jumpToPage etc.):
pageController.addListener(() {
if (pageController.position.userScrollDirection == ScrollDirection.reverse) {
pageController.nextPage(duration: const Duration(milliseconds: 60), curve: Curves.easeIn);
} else if (pageController.position.userScrollDirection == ScrollDirection.forward) {
pageController.previousPage(duration: const Duration(milliseconds: 60), curve: Curves.easeIn);
}
});
The issue is with the user settings, how the end-user has set the scrolling to happen with his mouse. I have a Logitech mouse that allows me to turn on or off the smooth scrolling capability via Logitech Options. When I enable smooth scrolling it works perfectly and scrolls as required but in case of disabling the smooth scroll it gets disabled on the project as well. The behavior is as set by the end-user.
Still, if there's a requirement to force the scroll to smooth scroll than can only be done by setting relevant animations. There's no direct way as of now.

How to get info from multiple widgets hovered over simoultaneously?

Issue
As per the drawing below I have a 4x4 grid of Widgets. The red line indicates the touch gesture I make. The green coloured squares are the squares the gesture touches. The blue coloured squares are the ones not touched by the gesture.
How can I make flutter get all the widgets i touch this way and store a reference so that I can access their content (for example an image or a string)?
What did I do so far?
I was looking at the "Draggable" widget type, it works for dragging a single widget and I could get that to work with a single widget. But I could not get it to work with multiple widgets being dragged over/touched this way. So I suspect I may need another solution. At this time I am just not sure what could make this functionality work.
Example image
Thanks for your help.
Please try the below example. You may need to modify it as per your requirement.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark()
.copyWith(scaffoldBackgroundColor: Color.fromARGB(255, 18, 32, 47)),
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(body: CustomPage());
}
}
class CustomPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return CustomPageState();
}
}
class CustomPageState extends State<CustomPage> {
double progress = 0;
var arr = [
[false, false, false],
[false, false, false],
[false, false, false]
];
var keys = [
[new GlobalKey(), new GlobalKey(), new GlobalKey()],
[new GlobalKey(), new GlobalKey(), new GlobalKey()],
[new GlobalKey(), new GlobalKey(), new GlobalKey()]
];
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blueAccent,
child: Center(
//Wraps the second container in RawGestureDetector
child: Center(
child: GestureDetector(
onHorizontalDragUpdate: (details) {
changeState(details.globalPosition);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(
3,
(i) => Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(
3,
(j) => Container(
key: keys[i][j],
margin: EdgeInsets.all(2),
color: arr[i][j] ? Colors.green : Colors.red,
width: 50,
height: 50,
)),
)),
),
)),
),
);
}
void changeState(Offset pos) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Rect re = _getWidgetGlobalRect(keys[i][j]);
if (re.contains(pos)) {
selectItem(i, j);
}
}
}
}
Rect _getWidgetGlobalRect(GlobalKey key) {
RenderBox renderBox = key.currentContext.findRenderObject();
var offset = renderBox.localToGlobal(Offset.zero);
return Rect.fromLTWH(
offset.dx, offset.dy, renderBox.size.width, renderBox.size.height);
}
void selectItem(int i, int j) {
if (arr[i][j]) {
return;
}
setState(() {
arr[i][j] = !arr[i][j];
});
}
}