我有这个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倍将来的功能。
game.cycle()函数供参考:
Future cycle(Function cBack) async {
for (int i in Range(50)) {
if (!shouldFinish) {
cBack(i);
///Does things.
到目前为止,我只是在屏幕上使用文本作为_progress
值。该vlaue会正确打印(每tot时间一次),但_progress
在功能末尾显示唯一更新的文本。我究竟做错了什么?
我尝试使用谷歌搜索方法,但没有发现任何问题。这可能吗?
编辑1。使用RémiRousselet提供的答案,我仍然无法使代码正常工作。仅在流结束时才更新小部件。
这是代码。
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 (Channel beta, v1.5.4-hotfix.2, on Microsoft Windows [Versione 10.0.17134.706], locale it-IT) • Flutter version 1.5.4-hotfix.2 at • Framework revision 7a4c33425d (8 days ago), 2019-04-29 11:05:24 -0700 • Engine revision 52c7a1e849 • Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)
Future
您可能需要一个而不是一个Stream
。
Future
仅在它们完全完成时才发出值。因此,我们不能使用它们来表示随时间变化的值(此处是进度指示器)。
甲Stream
另一方面可以发射的次数不受限制。
这是cycle
函数的实现,每次更新时都会发出当前进度:
Stream<double> cycle() async* {
for (int i in Range(50)) {
yield i / 50;
// TODO: does things
}
}
然后,您可以将其发送double
到CircularProgressIndicator
using中StreamBuilder
。
这是一个完整的示例:
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,
);
},
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句