V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
wly19960911
V2EX  ›  问与答

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

  •  
  •   wly19960911 · 2018-12-12 00:29:51 +08:00 · 1990 次点击
    这是一个创建于 1955 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我现在想实现的是,通过获取到的帖子列表,然后通过帖子的发贴人获取头像并且异步加载。现在有两个不同的代码,前者不能实现是因为 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(() { // 目的: 更新头像
            })
        }
    }
    
    // 成功,头像被一个个加载了。
    
    第 1 条附言  ·  2018-12-12 01:34:51 +08:00
    是头像没有被刷新,这个没有说清楚
    4 条回复    2018-12-12 21:17:49 +08:00
    wly19960911
        1
    wly19960911  
    OP
       2018-12-12 00:44:23 +08:00
    突然发现没有检查语法,手打的。。topics = await topicService.getTopics();
    haaro
        2
    haaro  
       2018-12-12 09:54:08 +08:00
    flutter 异步更新推荐使用 BLOC pattern,好像官方也有相关的建议
    https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1
    wly19960911
        3
    wly19960911  
    OP
       2018-12-12 10:31:19 +08:00
    @haaro #2 感谢,主要是官方的例子过于简单了,只有简单的拿数据,拿完就 setState 了,但是异步中又需要异步拿数据的情况下这个场景没看过。不过这个场景的确少,谁叫我用别人网站的 api 里面没有头像 url 呢
    wly19960911
        4
    wly19960911  
    OP
       2018-12-12 21:17:49 +08:00
    @haaro 我看了下,虽然 BLOC 的 pattern 是有用的,但是不是解决我的场景的,官网就是这种模式的,但是少了个 Repository,我这里也用了,只是取名 service 而已。

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

    但是为什么上一个失效我只能认为是做作用域问题了......
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5262 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 01:25 · PVG 09:25 · LAX 18:25 · JFK 21:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.