[flutter] 关于异步的问题(也有可能是作用域的问题)

2018-12-12 00:29:51 +08:00
 wly19960911

我现在想实现的是,通过获取到的帖子列表,然后通过帖子的发贴人获取头像并且异步加载。现在有两个不同的代码,前者不能实现是因为 setState 的作用域问题造成无法更新组件吗?

如果有更好的实现希望能说一下。

Future<void> _refresh() async { // 获取 topicList
    topics = topicService.getTopics();
    for (Topic topic in topicList) {
        userService.getUserByUsername(topic.author.name).then((user) {  // 异步执行
             topic.author = user // 更新用户信息 其中包括用户头像 url
             setState(() { // 目的: 更新头像
             })
        });
    }
    setState(() {  // 更新帖子列表
    })
}


// 失败,组件无法被更新

Future<void> _refresh() async { // 获取 topicList
    topics = topicService.getTopics();
    _getUserByTopics(topics);  // 异步执行
    setState(() { // 更新帖子列表
    })
}

Future<void> _getUserByTopics (List<Topic> topicList) async {
    for (Topic topic in topicList) {
        topic.author = await userService
               .getUserByUsername(topic.author.name); // 更新用户信息 其中包括用户头像 url
        setState(() { // 目的: 更新头像
        })
    }
}

// 成功,头像被一个个加载了。
1995 次点击
所在节点    问与答
4 条回复
wly19960911
2018-12-12 00:44:23 +08:00
突然发现没有检查语法,手打的。。topics = await topicService.getTopics();
haaro
2018-12-12 09:54:08 +08:00
flutter 异步更新推荐使用 BLOC pattern,好像官方也有相关的建议
https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1
wly19960911
2018-12-12 10:31:19 +08:00
@haaro #2 感谢,主要是官方的例子过于简单了,只有简单的拿数据,拿完就 setState 了,但是异步中又需要异步拿数据的情况下这个场景没看过。不过这个场景的确少,谁叫我用别人网站的 api 里面没有头像 url 呢
wly19960911
2018-12-12 21:17:49 +08:00
@haaro 我看了下,虽然 BLOC 的 pattern 是有用的,但是不是解决我的场景的,官网就是这种模式的,但是少了个 Repository,我这里也用了,只是取名 service 而已。

我的场景是 拿到 topic list,但是里面的 author 还没有获取到,如果采取正常的 await 我就会变成异步阻塞,没有拿到 author 头像 url 的时候一直会加载。我就打算现加载 topic 然后去获取头像 url,这样效果好不少。

但是为什么上一个失效我只能认为是做作用域问题了......

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/516706

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX