我正在为自己的FutureBuilder编写自己的MyFutureBuilder(除了使用我为其指定单独功能的快照数据时)。
typedef MyFutureBuilderBuildFunction<T> = Widget Function(T snapshotData);
class MyFutureBuilder<T> extends StatefulWidget {
final MyFutureBuilderBuildFunction<T> builder;
final Future<T> future;
MyFutureBuilder({this.future, @required this.builder})
: assert(builder != null);
@override
State<StatefulWidget> createState() {
return MyFutureBuilderState(future: future, builder: builder);
}
}
class MyFutureBuilderState<T> extends State<MyFutureBuilder<T>> {
MyFutureBuilderBuildFunction<T> builder;
Future<T> future;
MyFutureBuilderState({this.future, @required this.builder})
: assert(builder != null);
@override
Widget build(BuildContext context) {
return FutureBuilder<T>(
future: future,
builder: (context, snapshot) {
if (snapshot.hasData) {
return builder(snapshot.data);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Center(child: CircularProgressIndicator());
},
);
}
}
当我用
实例化它时Future<Article> _article;
MyFutureBuilder(
future: _article,
builder: (snapshotData) {
snapshotData的类型为动态,而不是 Article 。 无法根据_article的类型自动确定T类型吗?
当我将类型分别提供给MyFutureBuilder时(恕我直言,是多余的)
Future<Article> _article;
MyFutureBuilder<Article>(
future: _article,
builder: (snapshotData) {
snapshotData的类型当然是Article。
答案 0 :(得分:0)
在第一个代码中,应将返回的snapshotData转换为使用前所需的类型
Future<Article> _article;
MyFutureBuilder(
future: _article,
builder: (snapshotData) {
Article article = snapshotData as Article;
}
)