Get ListWheelScrollView selected item value

Viewed 172

I'm fairly new to flutter, and i created a Stateful Widget that creates a ListWheelScrollView with my own custom data like so:

class WeightScrollWheel extends StatefulWidget {
  final ScrollController scrollController;
  final int initialItem;
  late int _selectedItemIndex = initialItem;

  WeightScrollWheel({Key? key, required this.scrollController, this.initialItem = 50}) : super(key: key);

  @override
  State<WeightScrollWheel> createState() => _WeightScrollWheelState();
}


class _WeightScrollWheelState extends State<WeightScrollWheel> {

  List<Widget> getWeightList() {
    List<Widget> widgetsList = [];
    for (var i = 0; i < 300; i++) {
      widgetsList.add(_getWeightItem(i, i / 2));
    }
    return widgetsList;
  }

  _getWeightItem(int index, double val) {
    return SizedBox(
      width: double.infinity,
      height: 100,
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: AppPadding.p18),
            child: Container(
              height: 0.5,
              width: 175.0,
              color: _isCurrentSelected(index) ? ColorManager.primary : ColorManager.black,
            ),
          ),
          Text(
            val.toString() + (_isCurrentSelected(index) ? " kg" : "") ,
            style: TextStyle(color: _isCurrentSelected(index) ? ColorManager.primary : ColorManager.black),
          )
        ],
      ),
    );
  }

  bool _isCurrentSelected(int index) {
    return widget._selectedItemIndex == index;
  }


  @override
  Widget build(BuildContext context) {
    return ListWheelScrollView(
      itemExtent: 35.0,
      children: getWeightList(),
      controller: widget.scrollController,
      onSelectedItemChanged: (index) {
        setState(() {
          widget._selectedItemIndex = index;
        });
      },
    );
  }

}

I'm passing a controller to it from another widget, and i'm listening for changes, but i can't figure out how to get the current value. The only solution i found is passing the list to the WeightScrollWheel, and then getting the value by the index.. Is it possible to achieve and keep the list inside the WeightScrollWheel Widget? I don't want to 'clutter' the view widget that is using this widget.

0 Answers
Related