是否有任何回调告诉我何时“构建"?功能是在 Flutter 中完成的吗? [英] Is there any callback to tell me when "build" function is done in Flutter?
问题描述
我的屏幕上有一个 listView.我已经给它附加了一个控制器.我能够调用我的端点,接收响应,解析它并插入行.ListView 应该自动滚动.确实如此,但并不完美.我总是落后的项目.这是我的代码:
I have a listView in my screen. I have attached a controller to it. I am able to call my Endpoint, receive response, parse it and insert in row. ListView supposed to Scroll automatically. It does, but not in perfect way. I am always an item behind. This is my code:
@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()
函数.
The problem is, I am calling _toEnd()
function before the last item inserts in to the list. So, I am looking for a callback (if there is any) that tells me build()
is done. Then I call my _toEnd()
function.
这种情况下的最佳做法是什么?
What is the best practice in this case?
推荐答案
通用解决方案
只是想澄清一下,我没想到这个问题会引起如此多的关注.因此,我只回答了这个非常具体的案例.
正如在另一个答案中解释 WidgetsBinding
提供了一种添加一次 发布框架回调.
General solution
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
})
由于此回调将仅被调用一次,您每次构建时都想添加它:
As this callback will only be called a single time, you will want to add it every time you 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
}
这里有一个很好的例子说明这种效果.
关于在 Dart 中调度的广泛信息可以在这里找到.
There is a nice example illustrating that effect here.
Extensive information about scheduling in Dart can be found here.
这篇关于是否有任何回调告诉我何时“构建"?功能是在 Flutter 中完成的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!