【发布时间】:2019-01-29 08:04:01
【问题描述】:
我不希望每次重建小部件时都触发异步调用。 所以,我在 initState 中调用了 async 函数。
-
在 initState 中调用异步
@override void initState() { someAsyncCall().then((result) { setState() { _result = result; } }); } @override Widget build(BuildContext context) { if (_result == null) { reutrn new Container(); } return new SomeWidget(); } -
使用 FutureBuilder
@override void initState() { _future = someAsyncCall(); } @override Widget build(BuildContext context) { return new FutureBuilder( future: _future, builder: // do something ); }
这两种解决方案是否有任何副作用或不良做法?
我从 Flutter 修改了演示应用程序,以解释为什么我在 initSate 中调用异步。
1.打开app,打印main
2.推屏测试,打印测试,main
3.弹出测试,打印main
如果我在构建中调用异步函数,它会调用 3 次。
我想要的是,我需要一次异步函数调用,除非主要的 dispose / pop。
根据 Rémi Rousselet 的回答,在 initState 中调用 async 有点问题或错误。
那么,如何确保异步函数调用一次呢?
@override
Widget build(BuildContext context) {
print("build main");
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(onPressed: () {
Navigator.push(context, new MaterialPageRoute(builder: (context) {
return new Test();
}));
}),
],
),
)
);
}
class Test extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("build Test");
return new Scaffold(
body:
new FlatButton(onPressed: () {
Navigator.pop(context);
}, child: new Text("back"))
);
}
}
我需要做类似的事情吗
@override
Widget build(BuildContext context) {
if (!mounted) {
print("build main");
// aysnc function call here
}
}
【问题讨论】:
标签: flutter