AS
Günter Zöchbacher
正确指出,
FutureBuilder
是前进的道路。在您的案例中,它看起来是这样的:
import 'dart:async'; // you will need to add this import in order to use Future's
Future<int> fetchSavedItemNo() async { // you need to return a Future to the FutureBuilder
dir = wait getApplicationDocumentsDirectory();
jsonFile = new File(dir.path+ "/" + fileName);
fileExists = jsonFile.existsSync();
// you should also not set state because the FutureBuilder will take care of that
if (fileExists)
itemNo = json.decode(jsonFile.readAsStringSync())['item'];
itemNo ??= 0; // this is a great null-aware operator, which assigns 0 if itemNo is null
return itemNo;
}
@override
Widget build(BuildContext context) {
return FutureBuilder<int>(
future: fetchSavedItemNo(),
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
print('itemNo in FutureBuilder: ${snapshot.data}';
return Text('Hello');
} else
return Text('Loading...');
},
);
}
我也改变了你
fetchSavedItemNo
函数相应地返回
Future
.
较短的写作方式:
if (itemNo != null)
itemNo = 0;
以下是否使用
null-aware operator
:
itemNo ??= 0;
结论
正如您在我的代码中看到的,我包围了
Text
小部件
未来建筑
. 在颤振中,使用
Widget
我还介绍了
“正在加载…”
文本
可替换为
“你好”
文本
而
itemNo
仍在加载。
没有“黑客”可以删除加载时间并让您访问
伊藤诺
启动时。你要么这样做,惯用的,方式,或者你延迟你的启动时间。
每次加载时都需要使用占位符进行加载,因为它不是即时可用的。
附加
顺便说一句
,您也可以移除
“正在加载…”
文本
总是把你的
“你好”
文本,因为你会
从未见过
这个
“正在加载…”
文本
在你的情况下,事情发生得太快了。
另一个选择是逃避
ConnectionState
只需返回
Container
如果没有数据:
FutureBuilder<int>(
future: fetchSavedItemNo,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) => snapshot.hasData
? Text(
'Hello, itemNo: ${snapshot.data}',
)
: Container(),
)
以防你的用户界面没有受到影响
您可以在
initState
与我的
胎儿保存期
通过
初始状态
异步如下:
@override
void initState() {
super.initState();
fetchSavedItemNo(); // continue your work in the `fetchSavedItemNo` function
}