gpt4 book ai didi

flutter - future 运行两次,因为它在构建方法中,如何解决?

转载 作者:行者123 更新时间:2023-12-04 01:38:05 25 4
gpt4 key购买 nike

假设我有一个生成一些大文件的函数

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();
}
}
);
}

所以每当构建运行时, future 也会运行,显然它不应该运行。文档说

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: 可以毫无问题地运行多次,但是如果它是一些不应该运行多次的长时间操作怎么办?

我应该如何更改我的代码,使其执行现在的操作,而无需多次运行 future?

最佳答案

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();
}
}
);
}
}

关于flutter - future 运行两次,因为它在构建方法中,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com