有什么回调可以告诉我何时“构建"吗?功能是在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
}
特定(异步)
详细介绍昆特的评论:
@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屋!