为什么FutureBuilder在Flutter中没有接到电话?

时间:2018-07-04 06:35:03

标签: dart flutter

我的屏幕上有一个按钮,每当我点击_fetchPost()时,我都会呼叫它。此方法调用fetchPost()。在var post = ...行上设置断点时,我能够看到我的解析对象。但是,我的问题是builder将不会被调用。

我是Flutter的新手,所以我的代码错了吗?

void _fetchPost() {
    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;
          });
        }

        // By default, show a loading spinner
        return CircularProgressIndicator();
      },
    );
  }

  Future<Post> fetchPost() async {
    final response = await http.get('http://test.ethorstat.com/test.ashx');
    if (response.statusCode == 200) {
      // If server returns an OK response, parse the JSON
      var post = Post.fromJason(json.decode(response.body));
      return post;
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load post!');
    }
  }

1 个答案:

答案 0 :(得分:2)

FutureBuilder小工具。这意味着,要使其正常工作,您需要先将其插入小部件树

通过将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(() { // setState will not work here, I only used this StatelessWidget to show what I mean with inserting it into the build tree _result = res; }); } else if (snapshot.hasError) { setState(() { _result = snapshot.error; }); } // By default, show a loading spinner return CircularProgressIndicator(); }, ); Future<Post> fetchPost() async { final response = await http.get('http://test.ethorstat.com/test.ashx'); if (response.statusCode == 200) { // If server returns an OK response, parse the JSON var post = Post.fromJason(json.decode(response.body)); return post; } else { // If that response was not OK, throw an error. 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

我不确定您要如何实现FutureBuilder,但是如果要使用builder,则需要将其插入窗口小部件树并将窗口小部件返回到{{1} }。