- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有一个 Future 函数,它需要很长时间才能加载,而且它的工作原理基本上类似于视频渲染(它执行某些步骤 100 次)。有没有办法在小部件中显示进度?我尝试在 MyApp() 中设置一个全局变量,例如与框架对应的 int 并通过 setState(
) 我尝试重建小部件,但它没有用,应用程序卡住并且小部件没有得到更新。
这是函数:
int _progress = 0;
Future _cycleGame() async {
await game.cycle((int value) {
print(value);
setState(() {
_progress = value;
});
}).whenComplete(() {
setState(() {});
});
}
game.cycle()
是一个循环 50 次的 Future 函数。
game.cycle()函数供引用:
Future cycle(Function cBack) async {
for (int i in Range(50)) {
if (!shouldFinish) {
cBack(i);
///Does things.
截至目前,我只是在屏幕中使用一个文本作为 _progress
值。值被正确打印(每次一个),但显示 _progress
的文本仅在函数结束时更新。我做错了什么?
我尝试在谷歌上搜索如何操作,但一无所获。这可能吗?
编辑 1。使用 Rémi Rousselet 提供的答案,我仍然无法使代码正常工作。小部件仅在流结束时才会更新。
这是代码。
import 'dart:io';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Foo(),
);
}
}
class Foo extends StatefulWidget {
@override
_FooState createState() => _FooState();
}
class _FooState extends State<Foo> {
Stream<int> _cycleStream;
@override
void initState() {
super.initState();
_cycleStream = cycle();
}
Stream<int> cycle() async* {
for (int i = 0; i <= 50; i++) {
sleep(Duration(milliseconds: 100));
yield i;
this.setState(() {
});
// does things
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _cycleStream,
initialData: 0,
builder: (context, snapshot) {
return Center(
child: Text(snapshot.data.toString())
);
},
);
}
}
flutter 医生
[√] Flutter(Channel beta,v1.5.4-hotfix.2,在 Microsoft Windows [Versione 10.0.17134.706] 上,locale it-IT)
• Flutter 版本 1.5.4-hotfix.2 在
• 框架修订版 7a4c33425d(8 天前),2019-04-29 11:05:24 -0700
• 引擎版本 52c7a1e849
• Dart 版本 2.3.0(build 2.3.0-dev.0.5 a1668566e5)
最佳答案
您可能想要一个Stream
,而不是Future
。
Future
仅在它们完全完成时发出一个值。因此,我们不能使用它们来表示随时间变化的值(这里是进度指示器)。
另一方面,Stream
可以发出无限次。
这是您的 cycle
函数的一个实现,它会在每次更新时发出当前进度:
Stream<double> cycle() async* {
for (int i in Range(50)) {
yield i / 50;
// TODO: does things
}
}
然后您可以使用 StreamBuilder
将 double
发送到 CircularProgressIndicator
中。
这是一个完整的例子:
class Foo extends StatefulWidget {
@override
_FooState createState() => _FooState();
}
class _FooState extends State<Foo> {
Stream<double> _cycleStream;
@override
void initState() {
super.initState();
_cycleStream = cycle();
}
Stream<double> cycle() async* {
for (int i = 0; i <= 50; i++) {
yield i / 50;
// does things
}
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: _cycleStream,
initialData: 0,
builder: (context, snapshot) {
return CircularProgressIndicator(
value: snapshot.data,
);
},
);
}
}
关于dart - 有没有办法从 Flutter 中的 Future 函数获得反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787191/
我是一名优秀的程序员,十分优秀!