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(),
),
);
}
}
如您所見,我想"INFWARS_CH01_EP04"使用_scrollToItem函式通過特定資料跳轉到 ListView 中的特定專案,not by index or by position.
所以 ListView 的專案INFWARS_CH01_EP04將在頂部(滾動)。目前在頂部的是INFWARS_CH01_EP01.
有可能做到嗎?
uj5u.com熱心網友回復:
要滾動到特定專案,您可以:
使用以下方法查找特定專案
indexOf():使用
scrollable_positioned_list包滾動到該專案。
這是一個完整的作業示例:
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(),
),
);
}
}
另請參閱:flutter ListView 滾動到索引不可用
uj5u.com熱心網友回復:
我使用這個包修復它:https ://pub.dev/packages/scroll_to_index
因此,您可以在 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(),
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/442753.html
上一篇:Tabview滾動行為
