I want to show some items by category. I can do this with Map but they all depend on a single scrollController. Since there is no fixed number of categories, I cannot do it statically.
How can I create scrollController dynamically in Map.
These two lines give me error.
ScrollController scrollName = 'scrollName'+extra.id.toString();
ScrollController scrollName = new ScrollController();
My code
Column(
children: order!.extraOrders!.map((extra) {
ScrollController scrollName = 'scrollName'+extra.id.toString();
ScrollController scrollName = new ScrollController();
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: 'dymanicNameWillBe',
child: Row(
children: extra.items!.map((e) {
return Padding(
padding: const EdgeInsets.only(
right: 10.0,
bottom: 10,
top: 30,
left: 10),
...
First of all, error on these two lines are normal. Since you are trying to define a String to ScrollController object, Flutter will throw an error to this line;
ScrollController scrollName = 'scrollName'+extra.id.toString();
A value of type 'String' can't be assigned to a variable of type 'ScrollController'.
On second line, since you have already defined a variable (even if it is not a correct definition) named scrollName, Flutter will throw an error to this line;
ScrollController scrollName = new ScrollController();
The name 'scrollName' is already defined.
Also, when you want to define a scroll controller to a SingleChildScrollView the object should be a ScrollController, not a String.
Example code;
// Global scroll controllers list
List<ScrollController> controllersForExtraOrders = [];
// Arrange global scroll controller list
arrangeExtraOrderScrollControllers() {
order?.extraOrders?.forEach((extraOrder) {
ScrollController controller = ScrollController();
controllersForExtraItems.add(controller);
});
}
// Build UI with this global scroll controller list
Widget build(BuildContext context) {
...
Column(children: order!.extraOrders!.map((extra) {
// Get the extra order index.
int extraOrderIndex = order!.extraOrders!.indexOf(extra);
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
// Pass the controller at extraOrderIndex
controller: controllersForExtraItems[extraOrderIndex],
child: ....
);
...
}
...
}
Bonus; If you want to slide to next item, get the scroll controller for that dynamic list and do your stuff.
slideToNextItem(int extraOrderIndex) {
SlideController slideController = controllersForExtraItems[extraOrderIndex];
slideControllerExtra.animateTo(
slideControllerExtra.position.pixels + 190,
duration: Duration(milliseconds: 500),
curve: Curves.ease,
);
}
Happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With