我的屏幕上有一个列表视图.我已经给它装上了控制器.我能够调用我的端点、接收响应、解析它并将其插入行.ListView应该自动滚动.是的,但不是以完美的方式.我总是落在后面.这是我的代码:

@override
  Widget build(BuildContext context) {
    // Scroll to the most recent item
    if (equationList.length > 0) {
      _toEnd();
    }

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: EquList(equationList, _scrollController),
      floatingActionButton: new FloatingActionButton(
        onPressed: onFabClick,
        tooltip: 'Fetch Post',
        child: new Icon(isLoading ? Icons.pause : Icons.play_arrow),
      ),
    );
  }

  void _toEnd() {
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 250),
      curve: Curves.ease,
    );
  }

问题是,在最后一项插入列表之前,我调用了_toEnd()函数.因此,我正在寻找一个回调(如果有),它告诉我build()已经完成.然后我调用我的_toEnd()函数.

这种情况下的最佳实践是什么?

推荐答案

通解

Just to clear things up, I did not expect this question to attract so much attention. Hence, I only answered for this very specific case.
As explained in another answer WidgetsBinding offers a way to add a one time post frame callback.

WidgetsBinding.instance.addPostFrameCallback((_) {
  // executes after build
})

由于此回调将为only be called a single time,因此您需要在每次构建时添加它:

@override
Widget build(BuildContext context) {
  WidgetsBinding.instance.addPostFrameCallback((_) => afterBuild);
  return Container(); // widget tree
}

void afterBuild() {
  // executes after build is done
}

特定(异步)

详细说明Günter's条 comments :

@override
Widget build(BuildContext context) {
  executeAfterBuild();
  return Container();
}

Future<void> executeAfterBuild() async {
  // this code will get executed after the build method
  // because of the way async functions are scheduled
}

There is a nice example illustrating that effect here.
Extensive information about scheduling in Dart can be found here.

Flutter相关问答推荐

如何在Flutter 屏幕中添加箭头形状

为什么他们实例化类,然后丢弃该实例?

Flutter AppBar Animation反向调试

IsScrollable为True时如何删除Flutter 选项卡栏左侧填充

GitHub Actions工作流secret中的特殊字符未被保留

无法构建AndroidBundle 包或iOS等

在flutter web上渲染多个Youtube视频

'type' Icon '不是类型' IconData '的子类型

Flutter: pie_chart 插件动画滚动问题

Riverpod中stateNotiferProvider和notifierProvider的区别

Flutter Dart 功能弹出错误的小部件?

当项目较少时收缩列表视图

在 Flutter 中读取 Firebase 数据库数据时遇到问题

如何在 Flutter 执行通知时运行后台代码?

如何验证非表单字段?

如何让多个图标转到不同的网址

如何在屏幕按钮中排列 row() (我想在按钮中放置屏幕导航图标)

NoSuchMethodError:方法 '[]' 在 null 上被调用.我的信息流中的错误

更新未知文档 ID firebase\flutter 中的字段

Flutter 小部件中的视图和逻辑分离