问题
I have a listview
with some TextFields inside, I think that it will be cool to add the textfield once a user scrolls down,
For example:
We have 5 Elements in ListView after a user reaches the fifth element and continued scrolling down a new element is created. I couldn't find a solution for this task, I tried to check scrollposition for elements but unfortunately, I got an error
flutter: Another exception was thrown: NoSuchMethodError: The getter 'position' was called on null.
Here is the code..
ScrollController _controller;
@override
void initState() {
super.initState();
_controller = ScrollController();
}
FlatButton(
onPressed: () {
print(_controller.position.minScrollExtent);
},
child: Text('ds'),
),
ListView
- controller: _controller
回答1:
Here is the one solution if you want to add the new element on the end of the list view
ScrollController _controller;
ListView.builder(
controller: _controller,
itemCount: _items.length,
itemBuilder: (context, index) {
return ListTile(title: Text("Index : $index"));
},
)
@override
void initState() {
_controller = ScrollController();
_controller.addListener(_scrollListener);
super.initState();
}
_scrollListener() {
if (_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the bottom";
});
}
if (_controller.offset <= _controller.position.minScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the top";
});
}
}
in the maxScrollExtent
you need to add the element into the listview. I hope it will helps you.
For more information visit here
回答2:
For creating a ListView
with a dynamic number of children, you might want to check out the ListView.builder
factory constructor.
ListView.builder(
itemBuilder: (context, i) => Text('$i'),
)
Check out the "Working with long lists" tutorial for more information.
来源:https://stackoverflow.com/questions/57218907/create-a-new-element-once-a-user-scrolled-to-the-end-of-the-list-flutter