首页 > 解决方案 > RefreshIndicator 不更新 ListView 数据

问题描述

我正在尝试使用 RefreshIndicator 更新 ListView,但由于内容未更新,因此无法正常工作。我用一些初始数据 l 加载我的屏幕,当用户向下滚动时,我想加载一些额外的项目并将它们添加到我的 ListView 的顶部。该请求正在运行,但屏幕不是最新的。

我的代码:

Widget _answerTab(User user) {
    return FutureBuilder<void>(
      future: _getFirstQuestions(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return Center(
              child: CircularProgressIndicator(),
            );
            break;
          default:
            return RefreshIndicator(
                key: _refreshIndicatorKey,
                onRefresh: _refresh,
                child: ListView.builder(
                    padding: EdgeInsets.all(10.0),
                    itemCount: questions.length,
                    itemBuilder: (context, index) {
                      return ExpandableCard();
                    }));
        }
      },
    );
  }

Future<void> _refresh() async {
    List<Question> nextQuestions =
        await QuestionHelper().getLastQuestions(_lastQuestionTimestamp);
    if (nextQuestions != null) {
      questions.insertAll(0, nextQuestions);
      _lastQuestionTimestamp = DateTime.fromMicrosecondsSinceEpoch(
          nextQuestions[nextQuestions.length - 1]
              .timestamp
              .millisecondsSinceEpoch);
    }
  }

  Future<void> _getFirstQuestions() async {
    questions = await QuestionHelper().getLastQuestions(_lastQuestionTimestamp);
  }

标签: dartflutter

解决方案


在您的 _refresh 方法中调用 setState 以再次构建您的小部件。

setState(() {
    questions.insertAll(0, nextQuestions);
    _lastQuestionTimestamp = DateTime.fromMicrosecondsSinceEpoch(
        nextQuestions[nextQuestions.length - 1]
        .timestamp
        .millisecondsSinceEpoch
    );
});

推荐阅读