It's possible to jump to specific item by item data in ListView?
class Test extends StatelessWidget {
Test({Key? key}) : super(key: key);
final _list = <String>[
"INFWARS_CH01_EP01",
"INFWARS_CH01_EP02",
"INFWARS_CH01_EP03",
"INFWARS_CH01_EP04",
"INFWARS_CH01_EP05",
];
void _scrollToItem() {
final specificItem = "INFWARS_CH01_EP04";
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: _list.length,
itemBuilder: (context, index) {
final data = _list[index];
return Text(data);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scrollToItem(),
),
);
}
}
as you can see, I want to jump to specific item in ListView by specific data "INFWARS_CH01_EP04"
using _scrollToItem
function, not by index or by position
.
So the item ListView for INFWARS_CH01_EP04
will be in the top (scrolled). For now in the top is INFWARS_CH01_EP01
.
It's possible to do it?
CodePudding user response:
To scroll to a specific item you can:
Find the specific item using the
indexOf()
method:Use the
scrollable_positioned_list
package to scroll to that item.
Here is a complete working example:
class Test extends StatelessWidget {
Test({Key? key}) : super(key: key);
ItemScrollController _scrollController = ItemScrollController();
final _list = <String>[
"INFWARS_CH01_EP01",
"INFWARS_CH01_EP02",
"INFWARS_CH01_EP03",
"INFWARS_CH01_EP04",
];
void _scrollToItem() {
final specificItem = "INFWARS_CH01_EP04";
_scrollController.jumpTo(index: _list.indexOf(specificItem));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ScrollablePositionedList.builder(
itemScrollController: _scrollController,
itemCount: _list.length,
itemBuilder: (context, index) {
final data = _list[index];
return Text(data);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scrollToItem(),
),
);
}
}
See also: flutter ListView scroll to index not available
CodePudding user response:
I fix it using this package: https://pub.dev/packages/scroll_to_index
So you can scroll / jump to specific item by index / by item data in ListView.
class Test extends StatelessWidget {
Test({Key? key}) : super(key: key);
AutoScrollController _scrollController = AutoScrollController();
final _list = <String>[
"INFWARS_CH01_EP01",
"INFWARS_CH01_EP02",
"INFWARS_CH01_EP03",
"INFWARS_CH01_EP04",
];
void _scrollToItem() async {
final specificItem = "INFWARS_CH01_EP04";
final index = _list.indexOf(specificItem);
await _scrollController.scrollToIndex(
index,
preferPosition: AutoScrollPosition.begin,
);
await _scrollController.highlight(index);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: _scrollController,
itemCount: _list.length,
itemBuilder: (context, index) {
final data = _list[index];
return AutoScrollTag(
key: ValueKey(index),
controller: _scrollController,
index: index,
child: Text(data),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scrollToItem(),
),
);
}
}