我有一个定制的Flutter 小部件,它接收一个Future作为它的构造函数的参数,里面有FutureBuilder
个.
我想增加在连接错误的情况下重新运行这个future 的能力,但问题是第一次使用后,future 是"用尽"的.所以我需要一些方法来创建一个future 的副本,作为一个参数在用户每次按下重新加载按钮时使用FutureBuilder
内的副本.
import 'package:flutter/material.dart';
class CustomFutureBuilder<T> extends StatefulWidget {
final Future<T> future;
const CustomFutureBuilder({super.key, required this.future});
@override
State<CustomFutureBuilder<T>> createState() => _CustomFutureBuilderState<T>();
}
class _CustomFutureBuilderState<T> extends State<CustomFutureBuilder<T>> {
late Future<T> _future;
@override
void initState() {
// I need to use initState to initialize _future for the first usage of this widget
_future = widget.future; // ← here I want to create a future clone and use it instead of original
super.initState();
}
@override
void didUpdateWidget(covariant CommonFutureBuilder<T> oldWidget) {
_future = widget.future; // ← and here too
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const LinearProgressIndicator();
}
if (snapshot.hasError) {
debugPrint('Loading error: ${snapshot.error}');
return Column(
children: [
const Text(
'Loading error is occurred. Check the internet connection or try again later.'),
OutlinedButton(
onPressed: () {
setState(() {
// ← and maybe here too, I am not sure
});
},
child: const Text('Reload'),
),
],
);
}
final data = snapshot.data as T;
return …
},
);
}
}