将来运行两次,因为它在构建方法中,如何解决? [英] Future running twice because it's in build method, how to fix it?

查看:78
本文介绍了将来运行两次,因为它在构建方法中,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个可以制作一些大文件的功能

Say I have a function that makes some big file

Future<File> makeBigFile() async {
    // lots of processing
    return File("generated_file.txt");
}

@override
Widget build(BuildContext context) {
  return FutureBuilder(
    future: makeBigFile(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData && snapshot.data is File) {
        return Text("Success!");
      } else if (snapshot.connectionState==ConnectionState.done) {
        return Text("Error!");
      } else {
        return CircularProgressIndicator();
      }
    }
  );
}

因此,每当构建运行时,未来也将运行,这显然是不应该的.文档说

so whenever build runs, the future also runs which obviously it shouldn't. The docs say

将来一定要早一些,例如在State.initState,State.didUpdateConfig或State.didChangeDependencies中.构造FutureBuilder时,不得在State.build或StatelessWidget.build方法调用期间创建它.如果Future是与FutureBuilder同时创建的,则每次FutureBuilder的父代重建时,异步任务都将重新启动.

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

据我了解(尽管阅读并重新阅读了文档,但不多)FutureBuilder必须位于build()中,并且需要具有可以多次运行且没有问题的future:,但是如果这是一个不应该多次运行的长时间操作?

From what I understand (which isn't much, despite reading and re-reading the docs) FutureBuilder must be in build() and it needs to have future: that can run multiple times without problems but what if it's some long operation that shouldn't run multiple times?

我应该如何更改我的代码,使其执行现在的操作,但又不要多次运行将来的代码?

How should I change my code so it does what it does now but without running the future multiple times?

推荐答案

class BigFileWidget extends StatefulWidget {
  @override
  _BigFileWidgetState createState() => _BigFileWidgetState();
}

class _BigFileWidgetState extends State<BigFileWidget> {

  Future<File> fileFuture;

  @override
  void initState() {
    fileFuture = makeBigFile();
  };

  Future<File> makeBigFile() async {
    // lots of processing
    return File("generated_file.txt");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: fileFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData && snapshot.data is File) {
            return Text("Success!");
          } else if (snapshot.connectionState==ConnectionState.done) {
            return Text("Error!");
          } else {
            return CircularProgressIndicator();
          }
        }
    );
  }
}

这篇关于将来运行两次,因为它在构建方法中,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆