I am trying with https://github.com/flutter/codelabs/blob/master/startup_namer/step6_add_interactivity/lib/main.dart everything works fine but
when i keep debugging point in the onTab function( At line number 61) and breakpoint in ListView.Builder( At line number 38 ).
OnTab method is getting called first after that only ListView is getting called but i'm not able to understand how the index are correctly calculated in onTap method because th actual logic for index is placed at ListView.
Widget build(BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return const Divider();
final index = i ~/ 2;
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
final alreadySaved = _saved.contains(_suggestions[index]);
onTap: () {
setState(() {
if (alreadySaved) {
_saved.remove(_suggestions[index]);
} else {
_saved.add(_suggestions[index]);
}
});
Please explain how the index is getting calculated onTap.
CodePudding user response:
The favorite item is storing Set.
final _saved = <WordPair>{};
Once you click on favorite button, it checks whether it is already on _saved
final alreadySaved = _saved.contains(_suggestions[index]);
Now if alreadySaved
is true, it remove from the current tap item from the set.
if (alreadySaved) {
_saved.remove(_suggestions[index]);
}
If it alreadySaved
is false mean , _saved
doesnt contain the item, it add it.
else {
_saved.add(_suggestions[index]);
}
It is not storing the index, it is storing items value
And _suggestions
is holding all generated item.
CodePudding user response:
variable "index" is under the scope of Item builder and ListView and its onTap function can access the variable from its stack memory.
https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/