flutter - 在 Flutter 中完成 "build"函数时是否有任何回调告诉我?

标签 flutter

我的屏幕上有一个 listView。我已将 Controller 连接到它。我可以调用我的端点,接收响应,解析它并插入行。 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() 函数。

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

最佳答案

一般解决方案

只是为了澄清一下,我没想到这个问题会引起如此多的关注。因此,我只回答了这个非常具体的案例。
explained in another answer WidgetsBinding 提供了一种添加一次性 后帧回调的方法。

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评论:

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

有一个很好的例子illustrating that effect here .
关于Dart 中调度的详细信息 can be found here .

关于flutter - 在 Flutter 中完成 "build"函数时是否有任何回调告诉我?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51216448/

相关文章:

flutter - Flutter,如何配置textController

firebase - 如何将 firebase 存储中的图像显示到小部件中?

flutter - 如何更新 firestore 文档中的字段?

flutter - 如何使百分比指示器在 flutter 中以编程方式改变颜色?

flutter - 将字符串转换为字节数组

user-interface - 如何将listView转换为GridView抖动?

flutter - block 更新后无法使用 block 观察者

Flutter onChanged 和 onSaved 一起用于文本输入

flutter - 制作新小部件后清除类(class)列表

flutter - Flutter如何在没有Media Query的情况下获得亮度?