I am writing my own MyFutureBuilder for my FutureBuilders do the same thing every time (except working with the snapshot data for which I specify my separate function).
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());
},
);
}
}
When I instantiate it with
Future<Article> _article;
MyFutureBuilder(
future: _article,
builder: (snapshotData) {
the type of snapshotData is dynamic and not Article . Can't the type T be automatically be determined from the type of _article, Future?
When I seperately give the type to MyFutureBuilder (which is IMHO redundant)
Future<Article> _article;
MyFutureBuilder<Article>(
future: _article,
builder: (snapshotData) {
the type of snapshotData is of course Article.
In 1st code You should cast the returned snapshotData to the type you need before using it
Future<Article> _article;
MyFutureBuilder(
future: _article,
builder: (snapshotData) {
Article article = snapshotData as Article;
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.