I'm trying to make a ListView that auto-scrolls to the newest data point. I tired to do this by making a _scrollToBottom function that uses the .jumpTo method.
But i get a blank screen in the app, and
'child.parentData != null': is not true.
in the debug console.
Any suggestions on how i can implement auto-scrolling?
Here is the relevant portions of my current code:
ScrollController _scrollController = ScrollController();
_scrollToBottom(){ _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: DataShareWidget.of(context).stream,
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.hasError){ return Text(snapshot.error);}
if(snapshot.hasData){
_dataFormat(snapshot.data);
return ListView.builder(
itemCount: _listViewData.length,
controller: _scrollController,
reverse: true,
shrinkWrap: true,
itemBuilder: (context, index) {
_scrollToBottom();
return ListTile(
title: AutoSizeText(_listViewData[index], maxLines: 2),
dense: true,
);
},
);
}
}
);
}
You can make a dynamically created ListView by using the ListView. builder() constructor. This will create the ListView items only when they need to be displayed on the screen. It works like an Android RecyclerView but is a lot easier to set up.
What you need is to call _scrollToBottom()
method once the list is built fully.
Modification is your code (without StreamBuilder):
ScrollController _scrollController = ScrollController();
_scrollToBottom() {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());
return Scaffold(
body: ListView.builder(
itemCount: 50,
// itemCount: _listViewData.length,
controller: _scrollController,
reverse: true,
shrinkWrap: true,
itemBuilder: (context, index) {
return ListTile(
title: Text('Yo Dummy Text $index'),
// title: AutoSizeText(_listViewData[index], maxLines: 2),
dense: true,
);
},
),
);
}
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