首页 > 解决方案 > 列表 [index +1] 有效 [index - 1] 无效 (Flutter)

问题描述

我有一种方法可以跳到下一个列表项,效果很好,但是显示上一个列表项的方法似乎没有重新渲染。

当我打印到控制台时,列表项索引下降 1,但文本小部件不会像它增加 1 时那样更新。

我已经展示了下面的 2x 方法和构建的摘录。帮助!:)

void _skipFlashcard () {
    setState(() {
      int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
      var nextFlashcard = allFlashcards[currentIndex + 1];
      widget.flashcardToShow = nextFlashcard;
      print(widget.flashcardToShow.flashcardId);
    });
  }

  void _previousFlashcard () {
    int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
    var previousFlashcard = allFlashcards[currentIndex - 1];
    widget.flashcardToShow = previousFlashcard;
    print(widget.flashcardToShow.flashcardId);
  }

-------------------------
          Container(
            child: Row(
              children: <Widget>[
                Text(widget.flashcardToShow.flashcardId.toString()),

标签: listfluttersetstate

解决方案


将您的代码包装在 setState 中,这就是所有遗漏的 :-)

void _previousFlashcard () {
  setState() {
    int currentIndex = allFlashcards.indexOf(widget.flashcardToShow);
    var previousFlashcard = allFlashcards[currentIndex - 1];
    widget.flashcardToShow = previousFlashcard;
    print(widget.flashcardToShow.flashcardId);
  }
}

推荐阅读