FutureBuilder
是一个
首先将其插入小部件树
未来建筑
build
class FetchWidget extends StatelessWidget {
@override
Widget build(BuildContext context) => FutureBuilder<Post>(
future: fetchPost(),
builder: (BuildContext context, AsyncSnapshot<Post> snapshot) {
if (snapshot.hasData) {
String res = snapshot.data.parm1.toString() + snapshot.data.op + snapshot.data.parm2.toString();
setState(() {
_result = res;
});
} else if (snapshot.hasError) {
setState(() {
_result = snapshot.error;
});
}
return CircularProgressIndicator();
},
);
Future<Post> fetchPost() async {
final response = await http.get('http://test.ethorstat.com/test.ashx');
if (response.statusCode == 200) {
var post = Post.fromJason(json.decode(response.body));
return post;
} else {
throw Exception('Failed to load post!');
}
}
}
这不会编译,因为我只将您的代码复制到
StatelessWidget
setState
“将[…]添加到小部件树”
或者你可以用普通的
async
await
void _fetchPost() async {
final Post fetchedPost = await fetchPost();
final String res = fetchedPost.parm1.toString() + fetchedPost.op + fetchedPost.parm2.toString();
setState(() {
_result = res;
});
}
fetchPost
,但是如果你想使用
builder
.