I have the following list of expansionTiles inside a listView (to be able to scroll because there are more than 20 items), and when I tap on it, it shows another content in a panel. I want to open only one item per time (if I open one the other opened has to close) and this part is working now. See the code:
Expanded(
child: ListView.separated(
itemCount: snapshot.data[i].products.length,
key: Key('builder ${selected.toString()}'),
itemBuilder: (ctx, index) {
return ExpansionTile(
title: Row(
children: [
Text('${snapshot.data[i].products[index].code} - ', style: TextStyle(fontWeight: FontWeight.bold),),
Expanded(
child: Text('${snapshot.data[i].products[index].price == null ? "0.00" : NumberFormat.simpleCurrency(locale: 'pt_Br').format(snapshot.data[i].products[index].price)}', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),)
)
],
),
children: [
Container(
height: MediaQuery.of(context).size.height * 0.60,
width: MediaQuery.of(context).size.width,
child: ProductsColorWidget(snapshot.data[i].products[index], snapshot.data[i], refresh)
),
],
onExpansionChanged: ((newState) {
if(newState){
setState(() {
selected = index;
});
}else{
setState(() {
selected = -1;
});
}
}),
key: Key(index.toString()),
initiallyExpanded: index == selected,
);
},
separatorBuilder: (context, index) {
return Divider();
},
)
)
The problem is every time I open an item it rebuilds the screen and I have to scroll again to find the item I clicked on.
For example, I tapped in the last item, so, I want to see that item's content, but the list scrolls to the first item, and I have to scroll back to the last one to see its content;
What I want: Not scroll to the list init every time I tap in one item. Just tap in an item, open and show its content.. or scroll to the item tapped.
CodePudding user response:
ListView.builder(
itemCount: snapshot.data[i].products.length,
itemBuilder: (BuildContext context, int index) {
return ExpansionTile(
key: Key('builder ${selected.toString()}'),
initiallyExpanded: index == selected,