i want to have my list be controlled by arrow buttons, one that moves it forward one item and one that moves it backward one item something like this
i tried many packages and solutions but most of them goes to the end of the list or a fixed index number what i want is for the list to move to the next item in the list
It can be done only if you know the exact width to be scrolled. Use scrollController
ScrollController scrollController = ScrollController(
initialScrollOffset: 100, // or whatever offset you wish
keepScrollOffset: true,
);
You can use scroll_to_index package providing AutoScrollTag
.
class ST extends StatefulWidget {
const ST({Key? key}) : super(key: key);
@override
_STState createState() => _STState();
}
class _STState extends State<ST> {
final AutoScrollController controller = AutoScrollController();
late List<Widget> items;
int _currentFocusedIndex = 0;
@override
void initState() {
items = List.generate(
33,
(index) => AutoScrollTag(
key: ValueKey(index),
controller: controller,
index: index,
child: Container(
height: 100,
width: 100,
alignment: Alignment.center,
color: index.isEven ? Colors.deepOrange : Colors.deepPurple,
child: Text(index.toString()),
),
),
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
IconButton(
onPressed: () {
_currentFocusedIndex--;
if (_currentFocusedIndex < 0) {
_currentFocusedIndex = items.length - 1;
}
controller.scrollToIndex(_currentFocusedIndex,
preferPosition: AutoScrollPosition.begin);
setState(() {});
},
icon: const Icon(Icons.arrow_back_ios_new_sharp),
),
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
controller: controller,
children: items,
),
),
IconButton(
onPressed: () {
_currentFocusedIndex++;
if (_currentFocusedIndex > items.length) {
_currentFocusedIndex = 0;
}
controller.scrollToIndex(_currentFocusedIndex,
preferPosition: AutoScrollPosition.begin);
setState(() {});
},
icon: const Icon(Icons.arrow_forward_ios_sharp),
),
],
),
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.