when multiple instances of widget are rendered and the getValue method is called flutter throws the error ScrollController attached to multiple scroll views. I'm assuming this is because they all are using the same controller but I don't know a way to fix this without creating a separate widget for each time it is used. Is there a better way to fix this?
class NumScroller extends StatelessWidget{
final int max,min;
final double height,width;
final TextAlign alignment;
static ScrollController controller;
NumScroller({this.height,this.width,this.alignment,this.min,this.max, initialOffset}){
controller = new ScrollController(initialScrollOffset: initialOffset);
}
getValue() => (controller.offset~/height) + min;
@override
Widget build(BuildContext context) {
return new Container(
width: width,
height: height,
child: ListView.builder(itemBuilder: (context, index) {
return new Container(height: height, child:Text((max - index).toString(),textAlign: alignment,));
},
itemCount: max - min+1,
controller: controller,
physics: PageScrollPhysics(),
itemExtent: height,
)
);
}
}
Instead of using a static controller, you should have one controller per widget instance.
You cannot store your controller inside a StatelessWidget though (even if the compiler will allow it).
You need a StatefulWidget for that, or else when your widget is updated you will create a new controller again. Leading to weird behaviors.
Here the final code:
class NumScroller extends StatefulWidget{
final int max,min;
final double height,width;
final TextAlign alignment;
NumScroller({this.height,this.width,this.alignment,this.min,this.max, initialOffset});
@override
NumScrollerState createState() {
return new NumScrollerState();
}
}
class NumScrollerState extends State<NumScroller> {
final ScrollController controller = ScrollController();
getValue() => (controller.offset~/widget.height) + widget.min;
@override
Widget build(BuildContext context) {
return new Container(
width: widget.width,
height: widget.height,
child: ListView.builder(itemBuilder: (context, index) {
return new Container(height: widget.height, child:Text((widget.max - index).toString(),textAlign: widget.alignment,));
},
itemCount: widget.max - widget.min+1,
controller: controller,
physics: PageScrollPhysics(),
itemExtent: widget.height,
)
);
}
}
As you are telling when multiple instances are rendered
, you are getting this error. When your ScrollController
is multiple(one for one view), you will not get any problem. But you have only one ScrollController (because you have static).
Remove the static and it should work.
Please lemme know if it didn't work.
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