我正在尝试用以下内容构建一个列表视图:
预期的功能是列表视图应该一次显示一项。
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))
);
}在FAB的压力下-它增加了两次的项目。为什么会这样呢?我已经通过清除displayList并将所有项从0添加到当前索引来解决这个问题。
我试着设置listview的键,但没有解决这个问题。
任何帮助或洞察力。
发布于 2019-06-10 12:39:19
setState调用Widget的build方法来构建
所以这就是发生的事
单击FAB时调用onPressed方法。
_currentIndex = _currentIndex + 1;
displayList.add(simpleContentList[_currentIndex]);这将添加一个新项。
但是,build方法再次被调用,因此您再次在build方法displayList.add(simpleContentList[_currentIndex]);中添加列表中的元素。
解决方案1
删除
simpleContentList = getOOFirstContent();
displayList.add(simpleContentList[_currentIndex]);从build并将其添加到initState
解决方案2
删除
displayList.add(simpleContentList[_currentIndex]);,以便只添加一次元素。
有关StateFul Widget生命周期方法的详细信息,请参阅这里
https://stackoverflow.com/questions/56526089
复制相似问题