I have a horizontal scrolling ListView with an undetermined number of items inside.
How can I programatically scroll a specific item into the center of my screen?
Context: On the previous screen I have multiple items, and when I click on one, I need it to navigate to this screen and scroll the item selected on the previous screen to the center of the new screen.
My trouble is really just with the scrolling part.
Thanks in advance.
ListView:
final listViewController = ScrollController();
@override
Widget build(BuildContext context) {
return ListView.separated(
scrollDirection: Axis.horizontal,
physics: ClampingScrollPhysics(),
controller: listViewController,
padding: EdgeInsets.zero,
itemCount: testArray.length,
itemBuilder: (ctx, i) => Item(
testArray[i],
testArray[i] == 'item5' ? true : false,
() => {
// testing code for the scroll functionality
listViewController.animateTo(
i + MediaQuery.of(context).size.width / 2,
duration: Duration(seconds: 1),
curve: Curves.easeIn),
},
),
separatorBuilder: (ctx, i) => Padding(
padding: EdgeInsets.symmetric(horizontal: 6),
),
);
}
}
Item Widget:
class Item extends StatelessWidget {
final String itemName;
final bool selectedItem;
final VoidCallback navigationHandler;
Item(
this.itemName, this.selectedItem, this.navigationHandler);
@override
Widget build(BuildContext context) {
return Container(
height: double.infinity,
child: TextButton(
onPressed: navigationHandler,
child: Text(
itemName,
style: selectedItem
? Theme.of(context).textTheme.headline6?.copyWith(
fontSize: 22,
)
: Theme.of(context).textTheme.headline6?.copyWith(
color: Color(0xff707070),
),
),
),
);
}
}
