I have a ListView, where i change the Items in the List by clicking a button. Problem now is, that when i scroll down to the end of the list then click the Button, the Items change but the position of the list is still the same (so when i scrolled down and item #2 of my previous list was at the top, then item #2 of the new list will also be at the top). What i want is that the List starts at the top again and i have to scroll down again.
my main.dart:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List _list;
List _list1 = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'];
List _list2 = ['Element A', 'Element B', 'Element C', 'Element D', 'Element E', 'Element F'];
bool _isList1;
@override
void initState() {
_list = _list1;
_isList1 = true;
super.initState();
}
void _changeList() {
setState(() {
if (_isList1) {
_list = _list2;
_isList1 = false;
} else {
_list = _list1;
_isList1 = true;
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Schürer',
home: Scaffold(
appBar: AppBar(
title: Text('ListView'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text("Change List"),
onPressed: _changeList,
),
Expanded(
child: ListView(
children: _list
.map(
(item) => Card(
child: Container(
padding: EdgeInsets.all(50),
color: Colors.black26,
child: Text(item),
),
),
)
.toList(),
),
),
],
),
));
}
}
here you have to provide key to the ListView to differentiate two different listview. if you do not provide key then flutter think that both are same list view and it keep tracking listview using index of it.
what could be solution in your case if we consider first element of list as a key.
....
child: ListView(
key: ObjectKey(_list[0]),
children: _list
.....
This technique worked for me:
create the ScrollController
variable:
ScrollController _scrollController = ScrollController();
...
...
_scrollController.animateTo(0, duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn);
This is the description of animateTo()
by flutter:
Animates the position from its current value to the given value.
I called this function whenever the textfield
value is changed.
With a Scroll Controller you can do the following which will take you to the top of your ListView:
ScrollController _scrollController = ScrollController();
...
...
_scrollController.jumpTo(0);
Of course, you can change the index from 0 to any ListTile index, to jump to whichever ListTile you wish in your ListView.
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