gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:31:32 26 4
gpt4 key购买 nike

我的屏幕上有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com