首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ListView两次显示项目

ListView两次显示项目
EN

Stack Overflow用户
提问于 2019-06-10 12:06:47
回答 1查看 835关注 0票数 1

我正在尝试用以下内容构建一个列表视图:

预期的功能是列表视图应该一次显示一项。

代码语言:javascript
复制
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的键,但没有解决这个问题。

任何帮助或洞察力。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-10 12:39:19

setState调用Widget的build方法来构建

所以这就是发生的事

单击FAB时调用onPressed方法。

代码语言:javascript
复制
_currentIndex = _currentIndex + 1;
displayList.add(simpleContentList[_currentIndex]);

这将添加一个新项。

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

解决方案1

删除

代码语言:javascript
复制
simpleContentList = getOOFirstContent();
displayList.add(simpleContentList[_currentIndex]);

build并将其添加到initState

解决方案2

删除

代码语言:javascript
复制
displayList.add(simpleContentList[_currentIndex]);

,以便只添加一次元素。

有关StateFul Widget生命周期方法的详细信息,请参阅这里

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56526089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档