gpt4 book ai didi

android - ListView 显示项目两次

转载 作者:IT王子 更新时间:2023-10-29 07:18:36 25 4
gpt4 key购买 nike

我正在尝试使用以下内容在 flutter 中构建一个 ListView :

预期的功能是 ListView 应该一次显示 1 个项目。

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 添加到当前索引解决了这个问题。

我尝试将 key 设置为 listview,但这并没有解决问题。

感谢任何帮助或见解。

最佳答案

setState调用Widget的build方法进行构建

原来是这样

onPressed 方法在 FAB 被点击时调用

_currentIndex = _currentIndex + 1;
displayList.add(simpleContentList[_currentIndex]);

这添加了一个新项目

但是 build 方法又被调用了因此,您再次在构建方法 displayList.add(simpleContentList[_currentIndex]); 的列表中添加元素

解决方案1

移除

simpleContentList = getOOFirstContent();
displayList.add(simpleContentList[_currentIndex]);

build 并将其添加到 initState

解决方案2

删除

displayList.add(simpleContentList[_currentIndex]);

来自 setState 以便元素只添加一次


有关 StateFul 小部件生命周期方法的更多详细信息,请参阅 here

关于android - ListView 显示项目两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com