【发布时间】:2018-10-28 04:31:12
【问题描述】:
我正在试用 Flutter,但我无法让 UI 持续更新。我想在调用长时间运行的异步方法时显示一条状态消息,但是我在调用长时间运行的方法之前进行的 setState() 调用似乎不会导致我的 build() 方法被调用。
我创建了一个简单的示例,用于计算 25 到 30 之间随机选择的数字的斐波那契数。在我的示例代码/应用程序中,点击“calc”按钮调用 _calc()。 _calc() 选择一个随机数,设置状态消息“正在计算 $num 的 Fib ...”,并绑定到文本小部件 (_status) 并使用 setState() 更新它;然后调用 async _fib() 例程来计算数字;然后使用 setState() 用结果更新 _status。此外,build() 方法将 _status 的值打印到控制台,可用于查看何时调用 build()。
实际上,当按下按钮时,第一条状态消息既不会出现在调试控制台中,也不会出现在 UI 上。做了一些实验,我添加了一个伪睡眠函数,我在调用 _fib() 之前调用了它。 有时会导致第一个 setState() 调用正常工作 - 调用 build()。我睡得越久,它就越经常起作用。 (我使用的值从几毫秒到一整秒不等)。
所以我的问题是:我做错了什么?什么是正确的方法?使用伪睡眠显然不是正确的解决方案。
其他,可能不太相关的信息:我的开发环境是 Win10 机器上的 Android Studio 3.1.2。使用 Android SDK 27.0.3 和 Flutter beta 0.3.2。我的目标设备是运行 Android 8.1 的 pixel2 的模拟器。另外,很抱歉,如果我缺少“新”关键字令人不快,但从我在 Dart 2 发行说明中读到的内容来看,现在通常不需要。
import 'package:flutter/material.dart';
import "dart:async";
import "dart:math";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Debug Toy',
home: MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
@override
MyWidgetState createState() => MyWidgetState();
}
class MyWidgetState extends State<MyWidget> {
String _status = "Initialized";
final rand = Random();
Future sleep1() async {
return new Future.delayed(const Duration(milliseconds: 100),() => "1");
}
Future<Null> _resetState() async {
setState(() { _status = "State Reset"; });
}
Future<Null> _calc() async {
// calculate something that takes a while
int num = 25 + rand.nextInt(5);
setState(() { _status = "Calculating Fib of $num..."; });
//await sleep1(); // without this, the status above does not appear
int fn = await _fib(num);
// update the display
setState(() { _status = "Fib($num) = $fn"; });
}
Future<int> _fib(int n) async {
if (n<=0) return 0;
if ((n==1) || (n==2)) return 1;
return await _fib(n-1) + await _fib(n-2);
}
@override
Widget build(BuildContext context) {
print("Build called with status: $_status");
return Scaffold(
appBar: AppBar(title: Text('Flutter Debug Toy')),
body: Column(
children: <Widget>[
Container(
child: Row(children: <Widget>[
RaisedButton( child: Text("Reset"), onPressed: _resetState, ),
RaisedButton( child: Text("Calc"), onPressed: _calc, )
]),
),
Text(_status),
],
),
);
}
}
【问题讨论】:
标签: flutter