我想在flutter中打開頁面時運行下載Future函式,但是它被多次呼叫。
我想實作一個像本文中的第二個這樣的解決方案:
https://flutterigniter.com/future-async-called-multiple-times/
(在初始化后記住未來,以便不會多次呼叫 init 函式)但是在他的解決方案中,他像這樣初始化未來
Future<String> _future;
這在當前版本的 dart 中不再可能,我想知道是否有等價物,我嘗試使用 Late 關鍵字并將其初始化為 null,但兩者都不起作用。
這是當前的代碼以及我目前想要的代碼:
class _ARState extends State<AR> {
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((_) {
_downloadFiles();
});
}
Future<dynamic> _downloadFiles() async {
// some downloading function that is getting run multiple times ....
}
Widget build(BuildContext context) {
return FutureBuilder<dynamic>(
future: _downloadFiles(),
builder: /// stuff i want built
}
我想要它:
class _ARState extends State<AR> {
Future<dynamic> _future;
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((_) {
_downloadFiles();
});
}
Future<dynamic> _downloadFiles() async {
// some downloading function that is getting run multiple times ....
}
Widget build(BuildContext context) {
return FutureBuilder<dynamic>(
future: _future,
builder: /// stuff i want built
}
謝謝你的幫助!
uj5u.com熱心網友回復:
一種方法是通過檢查 if is_future來使您的異步函式可以為空并具有冪等性。如果它是空的,做作業;如果它不為空,則只需回傳現有的._futurenullFuture
class _ARState extends State<AR> {
Future<dynamic>? _future;
...
Future<dynamic> _downloadFiles() {
Future<dynamic> helper() async {
// Do actual downloading work here.
}
if (_future == null) {
_future = helper();
}
return _future;
}
Widget build(BuildContext context) {
return FutureBuilder<dynamic>(
future: _downloadFiles(),
...
}
}
uj5u.com熱心網友回復:
使用關鍵字嘗試下面的代碼late,但還有其他選項。我認為你不需要addPostFrameCallBack:
class _ARState extends State<AR> {
late Future<dynamic> _future;
@override
void initState() {
super.initState();
_future = _downloadFiles();
}
Future<dynamic> _downloadFiles() async {
}
Widget build(BuildContext context) {
return FutureBuilder<dynamic>(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasData || snapshot.data != null) {
// build your widget
}
// progress indicator or something while future is running
return ...;
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420294.html
標籤:
上一篇:串列的值未以正確的格式呈現
