小编典典

在Flutter中完成“ build”功能时是否有任何回调告诉我?

flutter

我的屏幕上有一个listView。我已经连接了一个控制器。我可以呼叫我的端点,接收响应,解析它并插入行中。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()函数。

在这种情况下,最佳做法是什么?


阅读 1113

收藏
2020-08-13

共1个答案

小编典典

一般解决方案

只是为了澄清问题,我没想到这个问题会引起如此多的关注。因此,我只针对这个非常特殊的情况回答。
正如在另一个答案中解释的那样,WidgetsBinding提供了一种添加 一次性 框架 回调的方法

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

由于此回调仅被调用一次,因此您希望在每次构建时都添加它:

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

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

具体(异步)

详细阐述Günter的评论:

@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
}

有一个很好的例子 说明这种效果
在这里

2020-08-13