I'm working with an indexed list in flutter, I found this lib: ScrollablePositionedList, when I put the action scrollTo / jumpTo on button tap, it works but when I put it before the returning built, it throws error:
E/flutter ( 3018): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: 'package:scrollable_positioned_list/src/scrollable_positioned_list.dart': Failed assertion: line 236 pos 12: '_scrollableListState != null': is not true.
Here is my code:
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
class ReadScreen extends HookWidget {
const ReadBibleScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
ItemScrollController idxCtrl = ItemScrollController();
/**Here, the code throw the Error */
bc.listenable.listen(
(p0) {
idxCtrl.scrollTo(index: p0, duration: Duration(seconds: 1));//-->Not Working
}
);
return Container(
decoration: BoxDecoration(gradient: kGradPink),
...
child:
/**Here, the code work */
IconButton(
onPressed: () {
idxCtrl.jumpTo(index: 10); //------------------------->Working
},
icon: Icon(Icons.tab)),
...
ScrollablePositionedList.builder(
itemScrollController: idxCtrl,
...
itemCount: ...
itemBuilder: (BuildContext context, int index) {
return Container(
...
CodePudding user response:
The code is executed line by line from top to bottom. In your case, ItemScrollController
is instantiated but not linked to ScrollablePositionedList
. It means that it doesn't aware of Object to which it belongs yet.
To make it work you can add the lines inside itemBuilder
class ReadScreen extends HookWidget {
const ReadBibleScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(gradient: kGradPink),
...
child:
IconButton(
onPressed: () {
idxCtrl.jumpTo(index: 10);
},
icon: Icon(Icons.tab)),
...
ScrollablePositionedList.builder(
itemScrollController: idxCtrl,
...
itemCount: ...
itemBuilder: (BuildContext context, int index) {
ItemScrollController idxCtrl = ItemScrollController();
bc.listenable.listen(
(p0) {
idxCtrl.scrollTo(index: p0, duration: Duration(seconds: 1));
}
);
return Container(
...
CodePudding user response:
Try wrapping your scrollTo
call inside an addPostFrameCallback
, this way the code will run after the build method has finished.
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
idxCtrl.scrollTo(index: p0, duration: Duration(seconds: 1));
});
...
CodePudding user response:
I used the answer here, it did the job as well: Flutter: Error thrown in some case using ScrollablePositionedList
sorry, the post was duplicated