Reputation: 628
I am trying to build a listview in flutter with the following :
The expected functionality is the listview should display 1 item at a time.
class SimpleContentScreen extends StatefulWidget {
@override
_SimpleContentScreenState createState() => _SimpleContentScreenState();
}
class _SimpleContentScreenState extends BaseState<SimpleContentScreen> {
List<SimpleContent> simpleContentList;
List<SimpleContent> displayList = List();
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
simpleContentList = getOOFirstContent();
displayList.add(simpleContentList[_currentIndex]);
return Scaffold(
appBar: buildAppBar("Introduction"),
body: _buildListView(),
floatingActionButton: _buildFab(),
);
}
FloatingActionButton _buildFab() => FloatingActionButton(
onPressed: () {
if( _currentIndex < simpleContentList.length - 1 ) {
setState(() {
_currentIndex = _currentIndex + 1;
displayList.add(simpleContentList[_currentIndex]);
});
}
},
child: Icon(Icons.navigate_next),
foregroundColor: Colors.white,
backgroundColor: Colors.blueGrey,
);
ListView _buildListView() => ListView.builder(
key: Key("_simple_content_list"),
itemCount: displayList.length,
itemBuilder: (context, position) {
return _buildItemView( displayList[position] );
}
);
_buildItemView(SimpleContent displayList) => Container(
padding: const EdgeInsets.all(12),
margin: EdgeInsets.fromLTRB(0, 8, 32, 8),
decoration: BoxDecoration(color: Colors.blueAccent),
child : new Text(
displayList.contentString,
style: buildTextSimpleContent(20))
);
}
Upon press of FAB - it's adding the items twice. Why is this? I have solved it by clearing the displayList and adding all items from 0 to the current index.
I tried setting key to the listview, but that didn't solve it.
Any help or insight appreciated.
Upvotes: 1
Views: 1140
Reputation: 3987
setState
calls the build
method of the Widget to build
So this is what's happening
onPressed
method is called when FAB is clicked
_currentIndex = _currentIndex + 1;
displayList.add(simpleContentList[_currentIndex]);
This adds a new item
But then build
method is again called
So you again add the element in the list in build method displayList.add(simpleContentList[_currentIndex]);
Remove
simpleContentList = getOOFirstContent();
displayList.add(simpleContentList[_currentIndex]);
from build
and add it to initState
delete
displayList.add(simpleContentList[_currentIndex]);
from setState
so that the element is added only once
For more details on StateFul Widget Lifecycle method refer here
Upvotes: 1