【发布时间】:2021-08-18 09:33:17
【问题描述】:
在 Flutter 中调用嵌套未来的最佳方式是什么?还是一般的颤振?
在我的应用程序中,我必须获取 当前用户(其数据位于 final storage = new FlutterSecureStorage();。
从这个用户,我调用了一个由 user id 提供的 API。这两个部分独立工作很好(很慢,但这是另一回事)。
在许多屏幕上,我必须调用异步函数,我使用Future.delayed 来执行此操作,而我的同事习惯使用这样的东西:
void initState() {
super.initState();
getCurrentUser();
}
void getCurrentUser() async {
user = await UserAuth.getCurrentUser();
}
这是我的嵌套期货。我需要在我的 initState 上加载当前用户来加载我的出版物。我必须在其中获取用户,因为它也可以是非当前用户(此功能将用于检索当前用户以及其他用户的出版物)。
class _UserPublicationsState extends State<UserPublications> {
List<Publication> listPublications;
List<Widget> list = [];
User user;
@override
void initState() {
super.initState();
Future.delayed(Duration.zero, () async {
await UserAuth.getCurrentUser().then((value) {
setState(() {
user = value;
UserWS.getPublicationsPerUsers(user).then((value) {
setState(() {
listPublications = value;
});
});
});
});
});
}
@override
Widget build(BuildContext context) {
if (listPublications == null) {
return FullPageLoading();
}
String title = "title";
return SafeArea(
child: Scaffold(
appBar: getSimpleAppBar(context, title),
body: SingleChildScrollView(
child: getSavedPublications(),
),
),
);
}
}
【问题讨论】:
-
1.我不明白“调用嵌套的未来”是什么意思。你等待
Futures。等待Future可能涉及在内部等待中间Futures,但这是等待者需要关注的实现细节。 2. 完全不清楚你为什么使用Future.delayed。如果只是创建一个async函数,那不是很有用。 3. 你通常应该只使用FutureBuilder。另请参阅:What is a Future and how do I use it? -
1) 通过嵌套,我理解“未来取决于另一个未来结果”。 2)我正在使用
Future.delayed,因为这就是我学会使用未来的方式。 3) 我可以在一个 raw 中使用 2 个 FutureBuilder 吗? -
2.使用
Future.delayed处理现有的Future毫无意义。为什么不使用Future.delayed来使用Future.delayed返回的Future?为什么不无限调用Future.delayed? 3. 我不明白“in a raw”是什么意思。 -
2) 我不明白,你能给我举个例子吗? 3)我的意思是:首先,获取用户;第二;让该用户调用另一个未来方法
标签: flutter nested future setstate